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 63 64 65 66 67 68 69
| #include <iostream> using namespace std;
class SortingArray { public: SortingArray(const int& size): size(size) { entry = new int[size]; } ~SortingArray() { if (entry != NULL) { delete [] entry; } } int operator[](int i) const { return entry[i%size]; } int& operator[](int i) { return entry[i%size]; } void sort() { int* tmp = new int[size]; mergeSort(entry, tmp, 0, size-1, true); delete [] tmp; } private: void mergeSort(int* arr, int* tmp, int beg, int end, bool inArr) { if (beg < end) { int mid = (beg + end) / 2; mergeSort(arr, tmp, beg, mid, !inArr); mergeSort(arr, tmp, mid+1, end, !inArr); if (inArr) { merge(arr, tmp, beg, mid, end); } else { merge(tmp, arr, beg, mid, end); } } else { if (!inArr) tmp[beg] = arr[beg]; } } void merge(int* arr1, int* arr2, int beg, int mid, int end) { int i = beg, j = mid+1, k = beg; while (i != mid+1 && j != end+1) { if (arr2[i] < arr2[j]) arr1[k++] = arr2[i++]; else arr1[k++] = arr2[j++]; } while (i != mid+1) arr1[k++] = arr2[i++]; while (j != end+1) arr1[k++] = arr2[j++]; } int* entry; int size; };
int main() { int size; cin >> size; SortingArray sa(size); for (int i = 0; i < size; ++i) { cin >> sa[i]; }
sa.sort();
for (int i = 0; i < size; ++i) { cout << sa[i] << ' '; } cout << endl; return 0; }
|