package com.hithomelabs.princeton1.module5;

import java.util.Comparator;

public class Insertion<E> implements MeasurableSort<E> {

    public void sort(E[] arr) {
        coreSortLogic(arr, null, null);

    }

    private void coreSortLogic(E[] arr, Comparator<E> cmp, SortingMetaData metaData) {
        if (arr == null) return;
        else {
            int N = arr.length;
            // * * swap arr[i] with each element greater to it's left
            for (int i = 1; i < N; i++) {
                int j = i;
                while (j >= 1 && less(arr[j], arr[j - 1], cmp, metaData)) {
                    exch(arr, j, j - 1, metaData);
                    j = j - 1;
                }
            }
        }
    }

    @Override
    public void sort(E[] arr, Comparator<E> cmp, SortingMetaData metaData) {
        if (metaData !=  null)
            metaData.startTime();
        coreSortLogic(arr, cmp, metaData);
        if (metaData !=  null)
            metaData.endTime();
    }

    @Override
    public void sort(E[] arr, Comparator<E> cmp) {
        coreSortLogic(arr, cmp, null);
    }
}

