1 /* 2 归并排序,需要多一倍的内存空间 3 速度和快速排序一样快 4 */ 5 6 #include<iostream> 7 #include<algorithm> 8 9 using namespace std; 10 11 template<class T> 12 void MergeSort(T *initlist, T *resultlist, const int l, const int m, const int n) 13 { 14 int i1, i2, iresult; 15 for (i1 = l, i2 = m + 1, iresult = l; i1 <= m && i2 <= n; iresult++) 16 { 17 if (initlist[i1] <= initlist[i2]) 18 { 19 resultlist[iresult] = initlist[i1]; 20 i1++; 21 } 22 else 23 { 24 resultlist[iresult] = initlist[i2]; 25 i2++; 26 } 27 } 28 std::copy(initlist+i1, initlist+ m+1, resultlist+iresult);//将比较完剩下的放进结果数组 29 std::copy(initlist+i2, initlist+ n + 1, resultlist+iresult); 30 31 } 32 33 template<class T> 34 void MergePass(T *initList,T *resultList,const int n,const int s) 35 { 36 int i; 37 for (i = 1; i <= n - 2 * s + 1; i += 2 * s) 38 { 39 MergeSort(initList,resultList,i,i+s-1,i+2*s-1); 40 } 41 if ((i + s - 1) < n)//有剩余的 42 MergeSort(initList, resultList, i, i + s - 1, n); 43 else 44 copy(initList + i, initList + n + 1, resultList + i); 45 } 46 47 template <class T> 48 void Merge(T *a, const int n) 49 { 50 T *tempList = new int[n + 1];//tempList[0]不用 51 for (int l = 1; l < n; l *= 2) 52 { 53 MergePass(a,tempList,n,l); 54 l *= 2; 55 MergePass(tempList,a,n,l); 56 } 57 delete[] tempList;//删除临时数组空间,防止内存泄漏 58 } 59 60 61 int main() 62 { 63 int a[] = { 0,23,47,81,95,7,14,39,55,62,74 }; 64 int b[11] = { 0 }; 65 MergeSort(a, b, 1, 4, 10); 66 for (int i = 1; i < 11; i++) 67 { 68 cout << b[i] << " "; 69 } 70 cout << endl; 71 72 int m[] = {0,26,5,77,1,61,11,59,15,48,19}; 73 int n[11] = { 0 }; 74 MergePass(m,n,10,1); 75 cout << "第一次归并:" << endl; 76 for (int i = 1; i < 11; i++) 77 cout << n[i] << " "; 78 cout << endl; 79 80 MergePass(n, m, 10, 2); 81 cout << "第二次归并:" << endl; 82 for (int i = 1; i < 11; i++) 83 cout << m[i] << " "; 84 cout << endl; 85 86 MergePass(m, n, 10, 4); 87 cout << "第三次归并:" << endl; 88 for (int i = 1; i < 11; i++) 89 cout << n[i] << " "; 90 cout << endl; 91 92 MergePass(n, m, 10, 8); 93 cout << "第四次归并:" << endl; 94 for (int i = 1; i < 11; i++) 95 cout << m[i] << " "; 96 cout << endl; 97 98 cout << "上面的都是中间结果的测试" << endl; 99 cout << "下面开始测试归并排序的最后结果" << endl; 100 int x[] = {0,26,5,77,1,61,11,59,15,48,19}; 101 Merge(x,10); 102 for (int i = 1; i < 11; i++) 103 cout << x[i] << " "; 104 cout << endl; 105 system("pause"); 106 return 0; 107 }
vs2015中运行结果: