java實現歸併排序,快速排序

快速排序

package com.ycit.sortSelect;

/**
 * @author 江鵬飛
 *	快速排序
 *	[11,4,3,6,5,8,7,12,9]
 *   low			  high
 *	思路:
 *	1.找到一個基準元素進行比較    分別從後往前  從前往後 找到 中間的值middle   此時middle 的位置就是基準元素的位置
 *	並且基準元素左邊的所有值都比基準元素小,右邊的所有元素都比基準元素大    然後再進行雙項迭代
 */
public class QuickSort {
	public void quick(int [] a){
		if(a.length>0){
			quickSort(a,0,a.length-1);
		}
	}
	public void quickSort(int a[],int low,int high){
		if(low<high){
		int middle = getMiddle(a,low,high);
		quickSort(a,0,middle-1);
		quickSort(a,middle+1,high);
	}
	}
	private int getMiddle(int[] a, int low, int high) {
		int temp = a[low];//基準元素
		while(low<high){
		while(low<high && a[high]>=temp){
			high--;
		}
		a[low]=a[high];
		while(low<high && a[low]<=temp){
			low++;
		}
		a[high]=a[low];
		}
		a[low]=temp; 
		
		return low;
	}
	public static void main(String[] args) {
		QuickSort q = new
				 QuickSort();
		int a[]= new int[] { 8, 3, 4, 5, 7, 1, 12, 33, 15 };
		q.quick(a);
		for (int i = 0; i < a.length; i++) {
			System.out.println(a[i]);
		}
	}

}

歸併排序

package com.ycit.sortSelect;

/**
 * @author 江鵬飛
 *	歸併排序
 *		[4,1,5,7,9,21,86,3,32,12]
 *		left	middle		right
 *	第一次分解: [4,1,5,7,9]      [21,86,3,32,12]
 *			left  mid  rg
 *	最終分解結果:[4] [1] [5] [7] [9] [21] [...]
 *	   兩兩比較   [1,4,5] [7,9,21] 
 *	三三比較 [1,4,5,7,9,21]
 *	對分解後的數組進行 合併
 *	
 *	思路:
 *		1.利用迭代的方法對數組進行分解    
 */
public class MergeSort {
	//[4,1,5,7,9,21,86,3,32,12]
	public void mergeSort(int a[],int left,int right){
		if(left<right){
			int middle = (left+right)/2;
			mergeSort(a,left,middle);// 把原數組左邊拆分成更小的數組
			mergeSort(a,middle+1,right);//把數組右半部分進行拆分成更小的數組  直到數組裏面有一個數時停止
			merge(a,left,middle,right);//合併
		}
	}

	private void merge(int[] a, int left, int middle, int right) {
		int [] tempArray = new int[a.length];
		int rightStart = middle+1;
		int temp = left;
		int third = left;
		while(left<=middle && rightStart<=right){
			if(a[left]<=a[rightStart]){
				tempArray[third++] = a[left++];
			}else{
				tempArray[third++] = a[rightStart++];
			}		
		}
		//如果右邊已經比較完畢 左邊還有元素需要比較  則現在左邊元素一定大於右邊元素 直接將左邊元素插入數組
		while(left<=middle){
			tempArray[third++]=a[left++];
		}											
		//如果左邊比較 完畢需要比較左邊 則同理把右邊元素插入到數組中
		while(rightStart<=right){
			tempArray[third++]=a[rightStart++];
		}
		//新數組排序完畢
		//將新的臨時數組賦值給我們要排序的數組 a
		while(temp<=right){
			a[temp]=tempArray[temp++];
		}
		
	}
	public static void main(String args[]){
		int a[] = new int[]{4,1,5,7,9,21,86,3,32,12};
		MergeSort mergeSort =new MergeSort();
		mergeSort.mergeSort(a, 0, a.length-1);
		for(int num:a){
			System.out.print("\t"+num);
		}
	}
}

 

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