package com.hithomelabs.princeton1.module6;

import com.hithomelabs.princeton1.module5.AbstractCustomSorts;

import java.util.Arrays;

public class Merge<E> extends AbstractCustomSorts<E> {
    private E[] auxArr;

    @Override
    public void sort(E[] arr) {
        auxArr = (E[]) new Object[arr.length];
        merge_sort(arr, 0, arr.length-1);
    }

    private void merge_sort(E[] arr, int low_index, int high_index){
        if(high_index - low_index > 0) {
            int mid_index = low_index + (high_index - low_index)/2;
            merge_sort(arr, low_index, mid_index);
            merge_sort(arr, mid_index + 1, high_index);

            // Copy array
            for(int i=low_index; i<= high_index; i++)
                auxArr[i] = arr[i];

            // Sort
            int low_index_ptr = low_index;
            int mid_index_ptr = low_index + (high_index - low_index)/2;
            int high_index_ptr = mid_index_ptr + 1;
            if(!less((Comparable<E>) auxArr[mid_index_ptr], auxArr[high_index_ptr])) {
                for (int i = low_index; i <= high_index; i++) {
                    if (low_index_ptr > mid_index_ptr) {
                        arr[i] = auxArr[high_index_ptr++];
                    } else if (high_index_ptr > high_index)
                        arr[i] = auxArr[low_index_ptr++];
                    else if (less((Comparable<E>) auxArr[low_index_ptr], auxArr[high_index_ptr]))
                        arr[i] = auxArr[low_index_ptr++];
                    else
                        arr[i] = auxArr[high_index_ptr++];
                }
            }
        }
    }
}


