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
| void MergeTwoArea(int arr[], int left, int mid, int right) { int fIdx = left; int rIdx = mid+1; int i;
int * sortArr = (int*)malloc(sizeof(int)*(right+1)); int sIdx = left;
while(fIdx<=mid && rIdx<=right) { if(arr[fIdx] <= arr[rIdx]) sortArr[sIdx] = arr[fIdx++]; else sortArr[sIdx] = arr[rIdx++];
sIdx++; }
if(fIdx > mid) { for(i=rIdx; i<=right; i++, sIdx++) sortArr[sIdx] = arr[i]; } else { for(i=fIdx; i<=mid; i++, sIdx++) sortArr[sIdx] = arr[i]; }
for(i=left; i<=right; i++) arr[i] = sortArr[i];
free(sortArr); }
void MergeSort(int arr[], int left, int right) { int mid;
if(left < right) { mid = (left+right) / 2;
MergeSort(arr, left, mid); MergeSort(arr, mid+1, right);
MergeTwoArea(arr, left, mid, right); } }
|