分治之歸並排序模版
阿新 • • 發佈:2017-08-14
code bsp n) nlogn 時間 復雜度 sort class cout
1 /* 2 歸並排序模版 3 對n個數進行排序 4 時間復雜度:O(nlogn); 5 利用分治思想,對比左半邊和右邊邊放入一個暫時的數組進行排序 6 */ 7 #include <iostream> 8 using namespace std; 9 const int maxn = 1005; 10 int a[maxn], t[maxn]; 11 void merge(int a[], int l, int m, int r) 12 { 13 int i = l, j = m + 1, x = m, y = r, k = 0; 14 while (i <= x && j <= y)15 if (a[i] < a[j]) t[k++] = a[i++]; 16 else t[k++] = a[j++]; 17 while (i <= x) t[k++] = a[i++]; 18 while (j <= y) t[k++] = a[j++]; 19 for (i = 0; i < k; ++i) 20 a[l + i] = t[i]; 21 } 22 void merge_sort(int a[], int l, int r) 23 { 24 if (l >= r) return; 25 int mid = (l + r) / 2; 26 merge_sort(a, l, mid); 27 merge_sort(a, mid + 1, r); 28 merge(a, l, mid, r); 29 } 30 void print() 31 { 32 for (int i = 0; i < 5; ++i) 33 cout << a[i] << " "; 34 cout << endl; 35 } 36 int main() 37 { 38 for (int i = 0; i < 5; ++i) 39 a[i] = 5 - i; 40 print(); 41 merge_sort(a, 0, 4); 42 print(); 43 return 0; 44 }
分治之歸並排序模版