1  /**
  2     This class sorts an array, using the merge sort algorithm.
  3  */
  4  public class MergeSorter
  5  {
  6     private int[] a;
  7  
  8     /**
  9        Constructs a merge sorter.
 10        @param anArray the array to sort
 11     */
 12     public MergeSorter(int[] anArray)
 13     {
 14        a = anArray;
 15     }
 16     
 17     /**
 18        Sorts the array managed by this merge sorter.
 19     */
 20     public void sort()
 21     {  
 22        if (a.length <= 1) return;
 23        int[] first = new int[a.length / 2];
 24        int[] second = new int[a.length - first.length];
 25        // Copy the first half of a into first, the second half into second
 26        for (int i = 0; i < first.length; i++) { first[i] = a[i]; }
 27        for (int i = 0; i < second.length; i++) 
 28        { 
 29           second[i] = a[first.length + i]; 
 30        }
 31        MergeSorter firstSorter = new MergeSorter(first);
 32        MergeSorter secondSorter = new MergeSorter(second);
 33        firstSorter.sort();
 34        secondSorter.sort();
 35        merge(first, second);
 36     }
 37  
 38     /**
 39        Merges two sorted arrays into the array managed by this merge sorter. 
 40        @param first the first sorted array
 41        @param second the second sorted array
 42     */
 43     private void merge(int[] first, int[] second)
 44     {  
 45        int iFirst = 0; // Next element to consider in the first array
 46        int iSecond = 0; // Next element to consider in the second array
 47        int j = 0; // Next open position in a
 48  
 49        // As long as neither iFirst nor iSecond is past the end, move
 50        // the smaller element into a
 51        while (iFirst < first.length && iSecond < second.length)
 52        {  
 53           if (first[iFirst] < second[iSecond])
 54           {  
 55              a[j] = first[iFirst];
 56              iFirst++;
 57           }
 58           else
 59           {  
 60              a[j] = second[iSecond];
 61              iSecond++;
 62           }
 63           j++;
 64        }
 65  
 66        // Note that only one of the two loops below copies entries
 67        // Copy any remaining entries of the first array
 68        while (iFirst < first.length) 
 69        { 
 70           a[j] = first[iFirst]; 
 71           iFirst++; j++;
 72        }
 73        // Copy any remaining entries of the second half
 74        while (iSecond < second.length) 
 75        { 
 76           a[j] = second[iSecond]; 
 77           iSecond++; j++;
 78        }
 79     }
 80  }