You are on page 1of 2

Merge Sort The merge sort uses the divide and conquer technique.

The merge sort algorithm divides the array into two partitions, then each of the subsequent partitions into two partitions, and so on until the partitions are of size 1. Now the size 1 partitions are merged together to form a sorted partition of size 2. Then the size 2 partitions are merged together to form and sorted partition of size 4. This continues until all the partitions are merged back together, giving us a sorted array. The running time of the merge sort is O(n log n) but is hardly ever used for main memory sorts. The additional work involved in copying to the temporary array and back slows the sort considerably. Here is an algorithm for the Merge sort.
public static void mergeSort(Comparable[] a) { Comparable[] tmpArray = new Comparable[a.length]; mergeSort(a, tmpArray, 0, a.length-1); } private static void mergeSort(Comparable[] a, Comparable[] tmpArray, int left, int right) { if (left < right) { int center = (left + right) / 2; mergeSort(a, tmpArray, left, center); mergeSort(a, tmpArray, center+1, right); merge(a, tmpArray, left, center+1, right); } } private static void merge(Comparable[] a, Comparable[] tmpArray, int leftPos, int rightPos, int rightEnd) { int leftEnd = rightPos - 1; int tmpPos = leftPos; int numElements = rightEnd - leftPos + 1; while (leftPos <= leftEnd && rightPos <= rightEnd) if (a[leftPos].compareTo(a[rightPos]) < 0) tmpArray[tmpPos++] = a[leftPos++]; else tmpArray[tmpPos++] = a[rightPos++]; while (leftPos <= leftEnd) // Copy rest of first half tmpArray[tmpPos++] = a[leftPos++]; while (rightPos <= rightEnd) // Copy rest of right half tmpArray[tmpPos++] = a[rightPos++]; for (int i = 0; i < numElements; i++, rightEnd--) a[rightEnd] = tmpArray[rightEnd]; }

Merge Sort (continued) Moves: All cases = 2 (n log n) Cmin = n/2 log(n) Cavg = Average of Cmin and Cmax Cmax = (n-1) log(n) The number of moves is fixed for all cases. The number of moves is dependent upon how many times the array is split up. The number of comparisons can vary. The best case would be when all the values in one sub-array are smaller than all the values in the other sub-array it is comparing to. When the small sub-array is exhausted the rest of the values from the other sub-array are copied without any comparisons being done. For example: sub-array #1: 10, 12 sub-array #3: 30, 32 Compare 10 with 30 and copy 10 to new array Compare 12 with 30 and copy 12 to new array sub-array #1 is exhausted, therefore copy all elements from sub-array #2 to new array - NO COMPARISONS NEEDED!

You might also like