前言
我们都知道BubbleSort这种排序算法不管从大到小排序,还是从小到大排序,都是相邻的两个进行比较,然后不符合条件时交换顺序。下面来看看引用类型是怎么进行BubbleSort的。
内容
需求:对下面几个日期进行BubbleSort排序;
用到的知识:数组为引用类型、排序过程中用到Compare()方法、重写了toString()方法;
内存分析
Demo
/*
作者:周丽同
说明:对引用类型(Date)进行BubbleSort
*/
public class TestDateSort{
public static void main(String[] args){
Date[] days = new Date[5];//定义一个日期数组
day[0] = new Date(2006,5,4);
day[1] = new Date(2006,7,4);
day[2] = new Date(2008,5,4);
day[3] = new Date(2004,5,9);
day[4] = new Date(2004,5,4);
bubbleSort(days);
//循环输出排序结果;
for(int i=0; i
System.out.printIn(days[i]);
}
}
//定义一个返回值为引用类型(数组)的bubbleSort方法;
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构造方法
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;
}
}
感谢您的宝贵时间······