歸併排序

1.算法思想
  首先,將R[0…n-1]看成是n個長度爲1的有序表,將相鄰的有序表成對歸併,得到n/2個長度爲2的有序表;然後,再將這些有序表成對歸併,得到4/n個長度爲4的有序表,如此反覆進行下去,最後得到一個長度爲n的有序。
  由於歸併是在相鄰的兩個有序表中進行的,因此,上述排序方法也叫二路歸併排序。如果歸併操作是在相鄰的多個有序表中進行,則叫多路歸併排序。這裏只討論二路歸併排序。

2.算法過程
(1)Merge()
  該算法用於將兩個有序表歸併爲一個有序表。

void Merge(int a[], int low, int mid, int high) {
    //申請一個額外空間,用來暫存歸併的結果
    int *temp = new int[high-low+1];
    int i=low, j=mid;
    int m=mid+1, n=high;
    int k=0; 
    //在兩個有序表中從前往後掃描
    while(i<=j && m<=n) {
        if(a[i]<=a[m])
            temp[k++] = a[i++];
        else
            temp[k++] = a[m++];
    }
    //將前一個有序表中剩餘的數據暫存到temp中
    while(i<=j) 
        temp[k++] = a[i++];
    //將後一個有序表中剩餘的數據暫存到temp中
    while(m<=n)
        temp[k++] = a[m++];
    //將temp中的數據覆蓋原來的數組      
    for(i=0;i<k;++i) 
        a[low+i] = temp[i];
    delete[] temp;
}

(2)歸併排序——分而治之
  算法的過程見下圖:
這裏寫圖片描述

void merge_sort(int a[], int low, int high) {
    //只有一個或無記錄時不須排序 
    if(low>=high) return;
    //取中間位置 
    int mid = (low+high)>>1;
    //遞歸分治
    merge_sort(a,low,mid);
    merge_sort(a,mid+1,high);
    //歸併
    Merge(a,low,mid,high);
}

3.性能分析
  歸併排序的時間效率與待排序的數據序列的順序無關。
(1)時間複雜度:

  • 平均 O(nlog2n )
  • 最好情況 O(nlog2n )
  • 最壞情況 O(nlog2n )

(2)空間複雜度:O(n)
(3)穩定性:穩定
(4)複雜性:較複雜

4.完整代碼

#include<iostream>
using namespace std;
//合併兩個有序表,並存儲到
void Merge(int a[], int temp[], int low, int mid, int high) {
    int i=low, j=mid;
    int m=mid+1, n=high;
    int k=0; 
    while(i<=j && m<=n) {
        if(a[i]<=a[m])
            temp[k++] = a[i++];
        else
            temp[k++] = a[m++];
    }

    while(i<=j) 
        temp[k++] = a[i++];
    while(m<=n)
        temp[k++] = a[m++];

    for(i=0;i<k;++i) 
        a[low+i] = temp[i];
}

void msort(int a[], int temp[], int low, int high) {
    if(low>=high) return;

    int mid = (low+high)>>1;
    msort(a,temp,low,mid);
    msort(a,temp,mid+1,high);
    Merge(a,temp,low,mid,high);
}

void merge_sort(int a[], int len) {
    int *temp = NULL;
    temp = new int[len];
    if(temp!=NULL){
        msort(a,temp,0,len-1);
        delete[] temp;
    }
}

int main() {
    int a[8] = {50,10,90.30,70,40,80,60,20};
    merge_sort(a,8);
    for(int i=0;i<8;++i) 
        cout<<a[i]<<" ";
    cout<<endl;
    return 0;
}

運行結果

這裏寫圖片描述

發佈了129 篇原創文章 · 獲贊 45 · 訪問量 24萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章