Here's how merge sort uses divide-and-conquer:
Divide by finding the number qq of the position midway between pp and rr. Do this step the same way we found the midpoint in binary search: add pp and rr, divide by 2, and round down.
Conquer by recursively sorting the subarrays in each of the two subproblems created by the divide step. That is, recursively sort the subarray array[p..q] and recursively sort the subarray array[q+1..r].
Combine by merging the two sorted subarrays back into the single sorted subarray array[p..r].
public class MergeSortJavaExample { public static void main(String[] args) { Integer[] a = {0, 2, 10, 5, -6, 7, 20, 2}; mergeSort(a); System.out.println(Arrays.toString(a)); } public static void mergeSort(Comparable [ ] a) { Comparable[] tmp = new Comparable[a.length]; mergeSort(a, tmp, 0, a.length - 1); } private static void mergeSort(Comparable [ ] a, Comparable [ ] tmp, int left, int right) { if( left < right ) { int center = (left + right) / 2; mergeSort(a, tmp, left, center); mergeSort(a, tmp, center + 1, right); mergeNumbers(a, tmp, left, center + 1, right); } } private static void mergeNumbers(Comparable[ ] a, Comparable[ ] tmp, int left, int right, int rightEnd ) { int leftEnd = right - 1; int k = left; int num = rightEnd - left + 1; while(left <= leftEnd && right <= rightEnd) if(a[left].compareTo(a[right]) <= 0) tmp[k++] = a[left++]; else tmp[k++] = a[right++]; while(left <= leftEnd) // Copy rest of first half tmp[k++] = a[left++]; while(right <= rightEnd) // Copy rest of right half tmp[k++] = a[right++]; // Copy tmp back for(int i = 0; i < num; i++, rightEnd--) a[rightEnd] = tmp[rightEnd]; } }
Output:
[-6, 0, 2, 2, 5, 7, 10, 20]
No comments:
Post a Comment