TopInsertion SortMerge Sort

Merge Sort

Our next sorting algorithm proceeds as follows:

The Java method to do it:


  public void sort(int[] array) {
     // create tempArray for use in merging
     int[] tempArray = new int[array.length];
     mergeSort(array, 0, array.length-1, tempArray);
    }

  /*
   * PRE: left and right are valid indexes of array.  
   *      tempArray.length == array.length
   * POST: Sorts array from left to right.
   */
  public void mergeSort(int[] array, int left, int right, int[] tempArray) {
    if (left < right) {
      int middle = (right + left) / 2;
      mergeSort(array, left, middle, tempArray);
      mergeSort(array, middle + 1, right, tempArray);
      merge(array, left, middle, right, tempArray);
    }
  }

The method merge takes the sorted elements in array[left..middle] and array[middle+1..right] and merges then together using the array tempArray, and then copies them back into array.

    
  /** PRE: left <= middle <= right and left,middle,right are valid 
   *  indices for array * tempArray.length == array.length 
   *  array[left..middle] and array[middle+1..right] must both be sorted.
   * POST: Merges the two halves (array[left..middle] and
   * array[middle+1..right]) together, and array[left..right] is then
   * sorted.
   */
   private void merge(int []array, int left, int middle,
                      int right, int[] tempArray) { 
     int indexLeft = left; 
     int indexRight = middle + 1; 
     int target = left;

    // Copy both pieces into tempArray.
    for (int i = left; i <= right; i++) {
      tempArray[i] = array[i];
    }
    
    // Merge them together back in array while there are
    // elements left in both halves.
    while (indexLeft <= middle && indexRight <= right) {
      if (tempArray[indexLeft] < tempArray[indexRight]) {
        array[target] = tempArray[indexLeft];
        indexLeft++;
      } else {
        array[target] = tempArray[indexRight];
        indexRight++;
      }
      target++;
    }

    // Move any remaining elements from the left half.
    while (indexLeft <= middle) {
      array[target] = tempArray[indexLeft];
      indexLeft++;
      target++;
    }

    // Move any remaining elements from the right half.
    while (indexRight <= right) {
      array[target] = tempArray[indexRight];
      indexRight++;
      target++;
    }
  }

TopInsertion SortMerge Sort