package com.hithomelabs.princeton1.module7;

import com.hithomelabs.princeton1.module5.AbstractCustomSorts;

public class ThreeWayQuick<E> extends AbstractCustomSorts<E> {
    @Override
    public void sort(E[] arr) {
        coreSortingLogic(arr);
    }

    private void coreSortingLogic(E[] arr) {
        int N = arr.length;
        threeWaySort(arr, 0, N - 1);
    }

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

        if(hi <= lo)
            return;
        int k = hi;
        int i = lo + 1;
        int j = lo;

        while (true) {
            if (((Comparable<E>) arr[i]).compareTo(arr[j]) < 0) {
                exch(arr, i, j++);
                i++;
            } else if (((Comparable<E>) arr[i]).compareTo(arr[j]) > 0)
                exch(arr, i, k--);
            else {
                i++;
            }

            if (k < i)
                break;
        }
        threeWaySort(arr, lo, j - 1);
        threeWaySort(arr, k + 1, hi);
    }

}
