1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| #include <iostream>
using namespace std;
void mergeArray(int* a, int first, int mid, int last, int* res) { int i = 0; int left = first; int right = mid + 1;
while(left <= mid && right <= last) { if(a[left] < a[right]) res[i++] = a[left++]; else res[i++] = a[right++]; }
while(left <= mid) res[i++] = a[left++];
while(right <= last) res[i++] = a[right++];
for(int j = 0; j < i; j++) a[first+j] = res[j]; }
void mergeSort(int* a, int first, int last, int* res) { if(first < last) { int mid = (first + last) / 2; mergeSort(a, first, mid, res); mergeSort(a, mid+1, last, res); mergeArray(a, first, mid, last, res);
} }
int main() { int num; cin >> num;
int* res = new int [num]; int* a = new int [num]; for(int i = 0; i < num; i++) cin >> a[i];
mergeSort(a, 0, num-1, res);
for(int i = 0; i < num; i++) cout << a[i] << ' '; cout << endl;
delete [] a; delete [] res; return 0; }
|