1. 程式人生 > >經典排序之歸並排序

經典排序之歸並排序

col 元素 -i family font 穩定排序 ack body 等於

歸並排序(Merge Sort)是建立在歸並操作上的一種有效的排序算法,它將已有序的子序列合並,得到完全有序的序列。

歸並排序的速度僅次於快速排序,時間復雜度為O(nlogn),為穩定排序算法,一般用於對總體無序,但是各子項相對有序的數列。

請看下述代碼:

public class Demo1 {

static int k=0;

public static void main(String []args){ int []arr = {9,8,7,6,5,4,3,2,1};

System.out.println("排序前:"+Arrays.toString(arr));

sort(arr); System.out.println("排序後:"+Arrays.toString(arr)); } public static void sort(int []arr){ int []temp = new int[arr.length];//在排序前,先建好一個長度等於原數組長度的臨時數組,避免遞歸中頻繁開辟空間 sort(arr,0,arr.length-1,temp); } private static void sort(int[] arr,int left,int right,int []temp){
if(left<right){ int mid = (left+right)/2; sort(arr,left,mid,temp);//左邊歸並排序,使得左子序列有序 sort(arr,mid+1,right,temp);//右邊歸並排序,使得右子序列有序 merge(arr,left,mid,right,temp);//將兩個有序子數組合並操作 } } private static void merge(int[] arr,int left,int mid,int right,int[] temp){
int i = left;//左序列指針 int j = mid+1;//右序列指針 int t = 0;//臨時數組指針 while (i<=mid && j<=right){ if(arr[i]<=arr[j]){ temp[t] = arr[i]; t++; i++; }else { temp[t] = arr[j]; t++; j++; } } while(i<=mid){//將左邊剩余元素填充進temp中 temp[t] = arr[i]; t++; i++; } while(j<=right){//將右序列剩余元素填充進temp中 temp[t] = arr[j]; t++; j++; } t = 0; //將temp中的元素全部拷貝到原數組中 while(left <= right){ arr[left] = temp[t]; left++; t++; }

System.out.println("第 "+(++k)+"次:"+Arrays.toString(arr));

}}

上述代碼的運行結果為:

排序前:[9, 8, 7, 6, 5, 4, 3, 2, 1]第 1次:[8, 9, 7, 6, 5, 4, 3, 2, 1]第 2次:[7, 8, 9, 6, 5, 4, 3, 2, 1]第 3次:[7, 8, 9, 5, 6, 4, 3, 2, 1]第 4次:[5, 6, 7, 8, 9, 4, 3, 2, 1]第 5次:[5, 6, 7, 8, 9, 3, 4, 2, 1]第 6次:[5, 6, 7, 8, 9, 3, 4, 1, 2]第 7次:[5, 6, 7, 8, 9, 1, 2, 3, 4]第 8次:[1, 2, 3, 4, 5, 6, 7, 8, 9]排序後:[1, 2, 3, 4, 5, 6, 7, 8, 9]

經典排序之歸並排序