package com.hithomelabs.princeton1.module6;

import com.hithomelabs.princeton1.module5.AbstractCustomSorts;

import java.util.Random;


public class Merge<E> extends AbstractCustomSorts<E> {
    @Override
    public void sort(E[] arr) {
        E[] aux = (E[]) new Object[arr.length];
        sort(arr, aux, 0, arr.length-1);
    }


    private void sort(E[] arr,E[] aux, int lo, int hi){

        if(hi<=lo) return;
        int mid = lo + (hi - lo)/2;
        sort(arr,aux, lo, mid);
        sort(arr,aux, mid+1,hi);
        merge(arr,aux,lo, mid, hi);

    }

    private void merge(E[] arr, E[] aux, int lo, int mid, int hi){


        for(int k=lo; k<=hi ;k++)
            aux[k] = arr[k];

        int i=lo, j = mid+1;

        for(int k = lo; k<=hi; k++){
            if(i>mid) arr[k] = aux[j++];
            else if(j>hi) arr[k] = aux[i++];
            else if(less((Comparable<E>) aux[i], aux[j] )) arr[k] = aux[i++];
            else arr[k] = aux[j++];
        }

    }

//    public static void main(String[] args){
//        Integer[] arrTest = new Integer[6];
//
//        for(int i=0;i<6;i++){
//            arrTest[i] = new Random().nextInt(100);
//            System.out.println(arrTest[i]);
//        }
//
//        System.out.println();
//
//        Merge<Integer> sortAlgo = new Merge<>();
//
//        sortAlgo.sort(arrTest);
//
//        for(Integer i: arrTest)
//            System.out.println(i);
//    }

}


