几种排序算法

public class Bubble {

	public static void main(String[] args) {
		int[] a = {38, 17, 16, 16, 7, 31, 39, 32, 2, 11};
		for(int i = 0;i<a.length;i++){
			for(int j=i+1;j<a.length;j++){
				if(a[j]<a[i]){
					exchange(a,i,j);	
				}
			}
		}
		for(Integer x:a){
			System.out.print(" "+x);
		}
	}
	
	public static void exchange(int[] array,int i, int j){
		if(i == j){return;}
		int temp = array[i];
		array[i] = array[j];
		array[j] = temp;
	}
}

  

public class Insert {

	public static void main(String[] args) {
		int[] a = {38, 17, 16, 16, 7, 31, 39, 32, 2, 11};
		for(int i = 1;i<a.length;i++){
			int temp = a[i];
			int j = i;
			for(;j>0;j--){
				if(a[j-1]>temp){
					a[j] = a[j-1];
				}else{
					break;
				}
			}
			a[j] = temp;
		}
		for(Integer x:a){
			System.out.print(" "+x);
		}
	}
}

  

public class Quick {

	public static void main(String[] args) {
		int[] a = {41,59,43,26,63,30,29,26,42};
		
		sort(a,0,a.length-1);
		
		for(Integer x:a){
			System.out.print(" "+x);
		}
	}


	private static void sort(int[] array, int lo, int hi) {
		if (lo >= hi) {
			return;
		}

		int toFinal = array[lo];
		int leftIdx = lo;
		int rightIdx = hi;

		int i = lo + 1;

		while (i <= rightIdx) {
			if (array[i] == toFinal) {
				i++;
			} else if (array[i] < toFinal) {
				exchange(array, leftIdx++, i++);
			} else {
				exchange(array, rightIdx--, i);
			}
		}

		sort(array, lo, leftIdx - 1);
		sort(array, rightIdx + 1, hi);
	}
	
	public static void exchange(int[] array,int i, int j){
		if(i == j){return;}
		int temp = array[i];
		array[i] = array[j];
		array[j] = temp;
	}
}

  

public class Select {

	public static void main(String[] args) {
		int[] a = {38, 17, 16, 16, 7, 31, 39, 32, 2, 11};
		for(int i = 0;i<a.length;i++){
			int selected = i;
			for(int j=i+1;j<a.length;j++){
				if(a[j]<a[selected]){
					selected = j;
				}
			}
			
		exchange(a,i,selected);	
		}
		for(Integer x:a){
			System.out.print(" "+x);
		}
	}
	
	public static void exchange(int[] array,int i, int j){
		if(i == j){return;}
		int temp = array[i];
		array[i] = array[j];
		array[j] = temp;
	}

}

  

posted @ 2014-04-04 09:03  Dream Catcher  阅读(196)  评论(0编辑  收藏  举报