coursera review---algorithms,Stanford---01---merge sort
merge sort is a typical divide & conquer algorithm,
merge is this algorithm's core subroutine,
merge:
merge two sorted subarrays into one sorted array
mergeSort:
divide input array to two subarrays leftArray and rightArray
mergeSort(leftArray);
mergeSort(rightArray);
merge these two subarrays
1 // merge two sorted subarrays a[low,low+1,...,mid] and a[mid+1,...,high] to a sorted array 2 void merge(int a[], int temp[], int low, int mid, int high) { 3 for (int i = low; i <= high; ++i) { 4 temp[i - low] = a[i]; 5 } 6 int i = 0; 7 int j = mid+1; 8 int k = low; 9 while (i <= mid-low && j <= high) { 10 a[k++] = (a[j] < temp[i]) ? a[j++] : temp[i++]; 11 } 12 while (i <= mid-low) { 13 a[k++] = temp[i++]; 14 } 15 } 16 17 void mergeSort(int a[], int temp[], int left, int right) { 18 if (right > left) { 19 int mid = (right + left) / 2; 20 mergeSort(a, temp, left, mid); 21 mergeSort(a, temp, mid + 1, right); 22 23 merge(a, temp, left, mid, right); 24 } 25 }
posted on 2013-08-16 22:21 haoyancoder 阅读(212) 评论(0) 收藏 举报
浙公网安备 33010602011771号