package com.wrox.algorithms.sorting;

import com.wrox.algorithms.lists.List;

public class InPlaceInsertionSortListSorter implements ListSorter {
    private final Comparator _comparator;

    public InPlaceInsertionSortListSorter(Comparator comparator) {
        assert comparator != null : "nie określono komparatora";
        _comparator = comparator;
    }

    public List sort(List list) {
        assert list != null : "nie określono listy";

        for (int i = 1; i < list.size(); ++i) {
            Object value = list.get(i);
            int j;
            for (j = i; j > 0; --j) {
                Object previousValue = list.get(j - 1);
                if (_comparator.compare(value, previousValue) >= 0) {
                    break;
                }
                list.set(j, previousValue);
            }
            list.set(j, value);
        }

        return list;
    }
}
