合並排序(分治法)
阿新 • • 發佈:2018-01-24
for 數組 數組a 想要 -s fin size 外部 ...
使用分治法進行合並排序,問題描述參見:https://www.cnblogs.com/jingmoxukong/p/4308823.html
算法核心:
//merge_sort.h #ifndef MERGE_SORT_H #define MERGE_SORT_H template <class Type> void MergeSort(Type a[], int n); #include "merge_sort.template" #endif
//merge_sort.template template <class Type> voidMergeSort(Type a[], int n) { Type *b = new Type[n]; int s = 1; while (s < n) { MergePass(a, b, s, n); //合並到數組b s += s; MergePass(b, a, s, n); //合並到數組a s += s; } delete b; } template <class Type> void MergePass(Type x[], Type y[], ints, int n) { int i = 0; while (i <= n - s * 2) { Merge(x, y, i, i + s - 1, i + 2 * s - 1); //合並大小為s的相鄰兩段子數組 i += s * 2; } if (i + s < n) //剩下的元素少於2s Merge(x, y, i, i + s - 1, n - 1); else for (int j = i; j <= n - 1; j++) y[j] = x[j]; } template<class Type> void Merge(Type c[], Type d[], int l, int m, int r) //合並c[l:m]和c[m+1:r]到d[l:r],其中c[l:m]和c[m+1:r]都是已經經過升序排好的數組 { int i = l, j = m + 1, k = l; while ((i <= m) && (j <= r)) { if (c[i] <= c[j]) d[k++] = c[i++]; else d[k++] = c[j++]; } if (i > m) for (int q = j; q <= r; q++) d[k++] = c[q]; else for (int q = i; q <= m; q++) d[k++] = c[q]; }
測試部分:
//main.cpp #include <iostream> #include "merge_sort.h" using namespace std; #define Type int //定義Type類型 int main() { int size; //數組大小 cout << "請輸入數組大小: "; cin >> size; Type *a = new Type[size]; //定義一個數組 cout << "請輸入數組中元素:" << endl; for (int i = 0; i < size; i++) { cin >> a[i]; } MergeSort(a, size); //對數組進行升序排序 cout << "輸出合並排序後的數組: " << endl; for (int j = 0; j < size; j++) { cout << a[j] << " "; } system("pause"); delete a; return 0; }
註意:
(1)由於這裏使用了模板函數,一般地模板函數地聲明和實現是不能分開的。(如果直接在main.cpp中加入extern void Mergesort(...)來調用其他.cpp文件中的MergeSort函數就回跳出“無法解析的外部符號,該函數已經在_main中被引用”的錯誤),如果想要在main.cpp中調用模板函數有兩種方法:
a、將模板函數的聲明和實現都放在同一個頭文件中,然後在Main.cpp中進行include,但是這樣子如果模板函數的的實現過長的話,會影響可讀性,所以一般推薦下面的方法;
b、將模板函數的聲明放在一個頭文件中,模板函數的實現放在一個.template中,然後在main.cpp中include這個頭文件就行了;
合並排序(分治法)