对象排序

来源:互联网 发布:相马光子知乎 编辑:程序博客网 时间:2024/06/07 18:09

这里就把排序算法与面向对象相结合了,很简单!!!!!!

package StructSort_1;public class MyDate {public int year;public int month;public int day;@Overridepublic String toString() {return  year + ", " + month + "," + day;}public MyDate(int year, int month, int day) {this.year = year;this.month = month;this.day = day;}}
package StructSort_1;public class Person {public MyDate brith;public String name;public double key;public Person(String name,MyDate brith, double key) {this.brith = brith;this.name = name;this.key = key;}@Overridepublic String toString() {return  brith + "," + name + ", " + key;}}
package StructSort_1;public class ObjectSort {public static void main(String[] args) {Person ps[] = new Person[6];ps[0] = new Person("Jack", new MyDate(1997, 1, 1), 23.12);ps[1] = new Person("Tom", new MyDate(1992, 10, 1), -1);ps[2] = new Person("Rose", new MyDate(1993, 5, 11), 66.6);ps[3] = new Person("Jerry", new MyDate(1991, 8, 8), 88.8);ps[4] = new Person("张三", new MyDate(1995, 9, 2), 22);ps[5] = new Person("王五", new MyDate(2017, 7, 12), 12.12);print(ps);bubbleSort(ps);print(ps);}    //这里使用的是冒泡排序public static void bubbleSort(Person ps[]) {for (int i = 0; i < ps.length - 1; i++) {for (int j = 0; j < ps.length - i - 1; j++) {if (ps[j].key > ps[j + 1].key) {// 用关键字的值比较swap(ps, j, j + 1); // 交换对象的引用}}}}private static void swap(Person[] ps, int j, int i) {Person temp = ps[i];ps[i] = ps[j];ps[j] = temp;}private static void print(Person ps[]) {for (Person p : ps) {   //增强for循环(只能读不能写)System.out.println(p);}System.out.println("-----------------");}}