import java.util.Arrays; public class MergeSorter extends Sorter { public MergeSorter(int numItems){ super(numItems); } public MergeSorter(int numItems, int seed){ super(numItems, seed); } @Override public void sort(){ recSort(data); } protected void recSort(int[] items){ if(items.length == 1) return; //arrays of one item are sorted int mid = (0 + items.length + 1)/2; //make a copy of the left half int[] leftHalf = Arrays.copyOfRange(items, 0, mid); //sort the left half of the array recSort(leftHalf); //make a copy of the right half int[] rightHalf = Arrays.copyOfRange(items, mid, items.length); //sort the right half of the array recSort(rightHalf); //merge the two halves merge(items, leftHalf, rightHalf); } protected void merge(int[] result, int[] leftHalf, int[] rightHalf){ int leftIndex = 0; int rightIndex = 0; int resultIndex = 0; //look at the left half and right half (both sorted) //choose the smaller of the smallest of each while(leftIndex < leftHalf.length && rightIndex < rightHalf.length){ //the left contains the smaller item if(leftHalf[leftIndex] < rightHalf[rightIndex]){ //copy it to the result result[resultIndex] = leftHalf[leftIndex]; //looking to fill the next item resultIndex++; //next time we will look at the next smallest item on the left leftIndex++; } //same for the right else{ result[resultIndex] = rightHalf[rightIndex]; resultIndex++; rightIndex++; } } //At this point, all items from one of the halves have been added to the result. //The other half still has at least one item in it. //clean up left half (since right half is empty) if(leftIndex < leftHalf.length){ for(int i = leftIndex; i < leftHalf.length; i++){ result[resultIndex] = leftHalf[i]; resultIndex++; } } //clean up right half (since the left half was empty) else if(rightIndex < rightHalf.length){ for(int i = rightIndex; i < rightHalf.length; i++){ result[resultIndex] = rightHalf[i]; resultIndex++; } } } }