排序算法之归并排序

来源:互联网 发布:stm32 压缩算法 编辑:程序博客网 时间:2024/06/14 09:54

1、迭代归并排序

将两个数当做已经排好序,再进行归并排序;然后再将上面两个排好序的数据进行归并排序;依次类推,最后将所有数据归并排序。如下图所示:
这里写图片描述


2、归并排序demo

#include <iostream>using namespace std;template <class T>void merge(T *initList, T *mergeList, int f, int s, int l);template <class T>void mergePass(T *initList, T *mergeList, const int n, const int s);template <class T>void mergeSort(T *initList, const int n);int main(int argc, const char *argv[]){    /*    cout << "初始数据:" << endl;    int a[] = {0, 1, 14, 45, 56, 16, 27, 46, 57, 78, 88};    int b[11] = {0};    for (int i = 1; i < 11; i++){        cout << a[i] << " ";    }    cout << endl;    cout << "开始测试merge..." << endl;    merge(a, b, 1, 4, 10);    for (int i = 1; i < 11; i++){        cout << b[i] << " ";    }    cout << endl;    cout << endl;    cout << "初始数据:" << endl;    int x[] = {0, 26, 5, 77, 1, 61, 11, 59, 15, 48, 19};    int y[11];    for (int i = 1; i < 11; i++){        cout << x[i] << " ";    }    cout << endl;    cout << "开始测试mergePass..." << endl;    mergePass(x, y, 10, 1);    for (int i = 1; i < 11; i++){        cout << y[i] << " ";    }    cout << endl;    mergePass(y, x, 10, 2);    for (int i = 1; i < 11; i++){        cout << x[i] << " ";    }    cout << endl;    mergePass(x, y, 10, 4);    for (int i = 1; i < 11; i++){        cout << y[i] << " ";    }    cout << endl;    mergePass(y, x, 10, 8);    for (int i = 1; i < 11; i++){        cout << x[i] << " ";    }    cout << endl;    cout << endl;*/    cout << "初始数据:" << endl;    int data[] = {0, 26, 5, 77, 1, 61, 11, 59, 15, 48, 19}; //注意:data[0],只是为了变成方便,不作为排序数据    for (int i = 1; i < 11; i++){        cout << data[i] << " ";    }    cout << endl;    cout << "开始测试mergeSort..." << endl;    mergeSort(data, 10);    for (int i = 1; i < 11; i++){        cout << data[i] << " ";    }    cout << endl;    return 0;}template <class T>void merge(T *initList, T *mergeList, int f, int s, int l){    int i, j, iResult;    for (i = f, j = s + 1, iResult = f; i <= s && j <= l; iResult++){        if (initList[i] < initList[j]){            mergeList[iResult] = initList[i];            i++;        }        else {            mergeList[iResult] = initList[j];            j++;        }    }    copy(initList+i, initList+s+1, mergeList+iResult);    copy(initList+j, initList+l+1, mergeList+iResult);}template <class T>void mergePass(T *initList, T *resultList, const int n, const int s){    int i;    for (i = 1; i <= n-2*s+1; i += 2*s)        merge(initList, resultList, i, i+s-1, i+2*s-1);    if ((i+s-1) < n)        merge(initList, resultList, i, i+s-1, n);    else        copy(initList+i, initList+n+1, resultList+i);}template <class T>void mergeSort(T *initList, const int n){    T *tempList = new int[n+1];    for (int i = 1; i < n; i *= 2){        mergePass(initList, tempList, n, i);        i *= 2;        mergePass(tempList, initList, n, i);    }    delete[] tempList;}
原创粉丝点击