1. 程式人生 > >利用氣泡排序對日期進行排序

利用氣泡排序對日期進行排序

package jave;

/*日期排序*/
public class DataSort {
	
	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++) {
			System.out.println(days[i]);//將數組裡的內容轉換成toString輸出
		}
		
	}
	
	
//對日期進行氣泡排序
	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;	
	}
	
	
	public static class Date {
			int year, month, day;
			Date(int y, int m, int d){
				year = y;
				month = m;
				day = d;
			}
			
//比較日期大小,先看年份,年份大就返回1,否則返回-1,如果年份相等,再比較月份,以此類推
			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;
			}		
		}
	
}