Java比較簡單的幾種排序算法

 1.快速排序的其中一種方式挖坑法

public class SortMethod {
	public static void main(String[] args) {
		int[] a={42,91,33,51,40,39,56,78,55,45,77,42};
		int start=0;
		int end=a.length-1;
		quickSort(a,start,end);
		for(int i=0;i<a.length;i++){
			System.out.print(a[i]+" ");
		}
	}
	private static void quickSort(int[] arr, int low, int high) {
		if (low < high) {
			// 找尋基準數據的正確索引
			int index = sort(arr, low, high);
			// 進行迭代對index之前和之後的數組進行相同的操作使整個數組變成有序
			quickSort(arr, low, index - 1);
			quickSort(arr, index + 1, high);
		}
	}
	private static int sort(int[] a, int low, int high) {
		int key = a[low];
		while (low < high) {
			while (low < high && a[high] >= key) {
				--high;
			}
			a[low] = a[high];
			while (low < high && a[low] < key) {
				++low;
			}
			a[high] = a[low];
		}
		a[low] = key;
		return low;
	}
}

2.冒泡排序圖解

3.選擇排序圖解

4.插入排序圖解

 

 

	//冒泡排序
	@Test
	public void BubbleSort(){
		int[] r={3,6,5,7,9,2,3,10};
		for(int i=0;i<r.length;i++){
			for(int j=0;j<r.length-i-1;j++){
				if(r[j]>r[j+1]){
					int temp=r[j];
					r[j]=r[j+1];
					r[j+1]=temp;
				}
			}
		}
		for(int b=0;b<r.length;b++){
			System.out.print(r[b]+" ");
		}
	}
	//選擇排序
	@Test
	public void SelectionSort(){
		int[] r={3,6,5,7,9,2,3,10};
		for(int i=0;i<r.length;i++){
			int min=i;
			for(int j=i+1;j<r.length-1;j++){
				if(r[min]>r[j]){
					min=j;
				}
			}
			int temp=r[i];
			r[i]=r[min];
			r[min]=temp;
		}
		for(int b=0;b<r.length;b++){
			System.out.print(r[b]+" ");
		}
	}
		//插入排序
		@Test
		public void InsertionSort(){
			int[] r={3,2,5,7,9,6,3,10};
			int curValue;
			int preIndex;
			for(int i=0;i<r.length-1;i++){
				curValue=r[i+1];
				preIndex=i;
				while(preIndex>=0 && curValue<r[preIndex]){
					r[preIndex+1]=r[preIndex];
					preIndex--;
				}
				r[preIndex+1]=curValue;
			}
			for(int b=0;b<r.length;b++){
				System.out.print(r[b]+" ");
			}
		}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章