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 data[] = {0, 26, 5, 77, 1, 61, 11, 59, 15, 48, 19};
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;
}
|