排序算法之歸併排序及Java實現

一、排序算法的分類

  1. 選擇排序(直接選擇排序堆排序
  2. 交換排序(冒泡排序快速排序
  3. 插入排序(直接插入排序希爾排序
  4. 歸併排序
  5. 桶式排序
  6. 基數排序

二、歸併排序的原理

歸併排序利用的是分治的思想實現的,對於給定的一組數據,利用遞歸與分治技術將數據序列劃分成爲越來越小的子序列,之後對子序列排序,最後再用遞歸方法將排好序的子序列合併成爲有序序列。合併兩個子序列時,需要申請兩個子序列加起來長度的內存,臨時存儲新的生成序列,再將新生成的序列賦值到原數組相應的位置。

三、歸併排序的實現


public class MergeSort {

    public static void merSort(int[] arr,int left,int right){

        if(left<right){
            int mid = (left+right)/2;
            merSort(arr,left,mid);//左邊歸併排序,使得左子序列有序
            merSort(arr,mid+1,right);//右邊歸併排序,使得右子序列有序
            merge(arr,left,mid,right);//合併兩個子序列
        }
    }
    private static void merge(int[] arr, int left, int mid, int right) {
        int[] temp = new int[right - left + 1];//ps:也可以從開始就申請一個與原數組大小相同的數組,因爲重複new數組會頻繁申請內存
        int i = left;
        int j = mid+1;
        int k = 0;
        while(i<=mid&&j<=right){
            if (arr[i] < arr[j]) {
                temp[k++] = arr[i++];
            } else {
                temp[k++] = arr[j++];
            }
        }
        while(i<=mid){//將左邊剩餘元素填充進temp中
            temp[k++] = arr[i++];
        }
        while(j<=right){//將右序列剩餘元素填充進temp中
            temp[k++] = arr[j++];
        }
        //將temp中的元素全部拷貝到原數組中
        for (int k2 = 0; k2 < temp.length; k2++) {
            arr[k2 + left] = temp[k2];
        }
    }
    public static void main(String args[]){
        int[] test = {9,2,6,3,5,7,10,11,12};
        merSort(test,0,test.length-1);
        for(int i=0; i<test.length;i++){
            System.out.print(test[i] + " ");
        }
    }

}

測試結果

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