java数组排序练习——使用冒泡法排序int型的数组,使用选择排序排序Date型的数组

java数组排序练习——使用冒泡法排序int型的数组,使用选择排序排序Date型的数组

PracticeSort.java

/*
	练习,
	使用冒泡法排序int型的数组
	使用选择排序法排序Date型的数组
*/
public class PracticeSort {
	public static void main(String[] args) {
		int[] a = {2, 4, 1, 3, 8, 7, 6, 5, 9, 0};
		
		bubbleSort(a);
		
		for(int i=0; i<a.length; i++){
			System.out.print(a[i] + " ");
		}
		System.out.println();
		
		/////////////////////////////////////////
		
		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);
		
		selectionSort(days);
		
		for(int i=0; i<days.length; i++){
			System.out.println(days[i]);
		}
				
	}
	
	//冒泡排序int数组
	public static int[] bubbleSort(int[] a){
		for(int i=a.length-1; i>0; i--){
			for(int j=0; j<=i-1; j++){
				if(a[j] > a[j+1]){
					int temp = a[j];
					a[j] = a[j+1];
					a[j+1] = temp;
				}
			}
		}
		return a;
	}
	
	//选择排序法排序Date型的数组
	private static void selectionSort(Date[] d) {
		int k;
		Date temp;
		for(int i=0; i<d.length; i++) {
			//k为最小的数的位置
			k = i;
			for(int j=k+1; j<d.length; j++) {
				//如果d[k]>d[j],将重新定义最小数的位置
				if(d[k].compare(d[j]) > 0) {			
					k = j;
				}
			}
			//如果k的位置不等于i的位置,交换
			if(k != i) {
				temp = d[i];
				d[i] = d[k];
				d[k] = temp;
			}
		}
	}
}

//定义日期类
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 PracticeSort.java

F:\java>java PracticeSort
0 1 2 3 4 5 6 7 8 9
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>

猜你喜欢

转载自mfcfine.iteye.com/blog/2383787