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