java使用冒泡排序引用类型的数组
TestDateSort.java
//对日期进行排序
public class TestDateSort {
public static void main(String[] args) {
//引用类型数组
Date[] days = new Date[5];
days[0] = new Date(2006, 5, 4);
days[1] = new Date(2006, 7, 4);
days[2] = new Date(2008, 5, 4);
days[3] = new Date(2004, 5, 9);
days[4] = new Date(2004, 5, 4);
//冒泡排序
bubbleSort(days);
for(int i=0; i<days.length; i++) {
//打印对象的引用,相当与直接调用toString(),需要重写toString()
System.out.println(days[i]);
}
}
//冒泡排序
public static Date[] bubbleSort(Date[] a){
int len = a.length;
//从底往上
for(int i = len-1;i>=1;i--){
//数组序号从小到大
for(int j = 0;j<=i-1;j++){
//比较日期大小
if(a[j].compare(a[j+1]) > 0){
//下标值没变,指向的对象改变了
Date temp = a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
return a;
}
}
//定义日期类
class Date {
int year, month, day;
Date(int y, int m, int d) {
year = y; month = m; day = d;
}
//比较日期大小
public int compare(Date date) {
return year > date.year ? 1
: year < date.year ? -1
: month > date.month ? 1
: month < date.month ? -1
: day > date.day ? 1
: day < date.day ? -1 : 0;
}
//重写toString()
public String toString() {
return "Year:Month:Day -- " + year + "-" + month + "-" + day;
}
}
F:\java>javac TestDateSort.java F:\java>java TestDateSort Year:Month:Day -- 2004-5-4 Year:Month:Day -- 2004-5-9 Year:Month:Day -- 2006-5-4 Year:Month:Day -- 2006-7-4 Year:Month:Day -- 2008-5-4 F:\java>