package Sorting;

public class MergeSorter extends Sorter{
    
    public MergeSorter(String filename){
        super("merge",filename);
    }

    void sort(){
        mergeSort(0,numbers.length-1);
    }

    void mergeSort(int leftIndex, int rightIndex){
        if(compare(leftIndex,rightIndex)<0){
            int middleIndex = (leftIndex+rightIndex)/2;
            mergeSort(leftIndex,middleIndex);
            mergeSort(middleIndex+1,rightIndex);
            merge(leftIndex,middleIndex,rightIndex);
        }
    }

    /**
     * merges subarray from leftIndex...middleIndex with subarray from middleIndex+1...rightIndex
     * @param leftIndex
     * @param middleIndex
     * @param rightIndex
     */
    void merge(int leftIndex, int middleIndex, int rightIndex){
        int sizeLeft=middleIndex-leftIndex+1;//add 1 to include both endpoints
        int sizeRight=rightIndex-middleIndex;//both endpoints already included, as middleIndex is part of left array
        int[] left=new int[sizeLeft];
        int[] right=new int[sizeRight];
        for(int i=0;i<sizeLeft;i++){
            left[i]=numbers[leftIndex+i];
        }
        for(int i=0;i<sizeRight;i++){
            right[i]=numbers[middleIndex+1+i];
        }
        int i=0, j=0;//indices of left and right array
        int k=leftIndex;//index of numbers array
        while(i<sizeLeft&&j<sizeRight){
            if(compare(left[i],right[j])<1){
                numbers[k]=left[i];
                i++;
            }
            else{
                numbers[k]=right[j];
                j++;
            }
            k++;
        }
        while(i<sizeLeft){
            numbers[k]=left[i];
            i++;
            k++;
        }
        while(j<sizeRight){
            numbers[k]=right[j];
            j++;
            k++;
        }
    }

}