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
| #include <iostream> using namespace std;
void MergeArray(int arr[], int l, int r, int mid) { int* temp = (int*)malloc((r-l+1)*sizeof(int)); int i=l, j = mid+1, k=0; while(i<=mid && j<=r) { if (arr[i] <= arr[j]) { temp[k++] = arr[i]; i++; } else { temp[k++] = arr[j]; j++; } } while(i<=mid) { temp[k++] = arr[i]; i++; } while(j<=r) { temp[k++] = arr[j]; j++; } for (i=0;i<k;i++) { arr[l+i] = temp[i]; } free(temp); }
void MergeSort(int arr[], int l, int r) { if (l < r) { int mid = (l + r)/2; MergeSort(arr, l, mid); MergeSort(arr, mid+1, r); MergeArray(arr, l, r, mid); } }
|