归并排序-C++

归并排序(MERGE-SORT)是利用归并的思想实现的排序方法,该算法采用经典的分治(divide-and-conquer)策略(分治法将问题(divide)成一些小的问题然后递归求解,而治(conquer)的阶段则将分的阶段得到的各答案"修补"在一起,即分而治之)。

#include<bits/stdc++.h>
using namespace std;

//1、将有二个有序数列a[first...mid]和a[mid+1...last]合并。
void mergearray(int a[], int first, int mid, int last, int temp[]){
    //i->m  j->n
    int i = first, j = mid+1;
    int m = mid,   n = last;
    int k = 0;

    while (i <= m && j <= n){
        if (a[i] <= a[j])
            temp[k++] = a[i++];
        else
            temp[k++] = a[j++];
    }
    
    while (i <= m)
        temp[k++] = a[i++];
    
    while (j <= n)
        temp[k++] = a[j++];
    
    //最后在重新赋值给a
    for (i = 0; i < k; i++)
        a[first + i] = temp[i];
}

//2、递归排序
void mergesort(int a[], int first, int last, int temp[]){
    //递归分解的结束条件就是只有一个数,那肯定就是有序的
    if(first<last){
        int mid=(first+last)/2;
        //左边排序
        mergesort(a, first, mid, temp);
        //右边排序
        mergesort(a, mid+1, last, temp);
        //两个合并
        mergearray(a, first, mid, last, temp);
    }
}


int main(){
    clock_t time_start=clock();
    int arrays[10]={5,8,6,3,4,7,9,1,0,2};
    //创造一个临时数组
    int *temp=new int [10];
    mergesort(arrays,0,9,temp);
    for(int a:arrays){
        cout<<a<<endl;
    }
    clock_t time_end=clock();
    cout<<1000*(time_end-time_start)/(double)CLOCKS_PER_SEC<<"ms"<<endl;
}

 

posted @ 2020-11-05 13:44  苗头hhh  阅读(87)  评论(0)    收藏  举报