A generic method for insertion Sort. - Java Data Structure

Java examples for Data Structure:Sort

Description

A generic method for insertion Sort.

Demo Code


//package com.java2s;

import java.util.Comparator;

public class Main {
    /**// www .  ja  v a  2  s. c  om
     * A generic method. Sorts the input array using an insertion sort and the
     * input Comparator object.
     * 
     * @param array
     *            -- the input array of objects to be sorted
     * @param mComparator
     *            -- the comparator to be used in the insertion sort
     */
    public static <T> void insertionSort(T[] array,
            Comparator<? super T> mComparator) {
        int i, j;
        for (i = 1; i < array.length; i++) {
            T index = array[i]; // object to be inserted
            // until the insertion point is found, shift items
            for (j = i; j > 0
                    && mComparator.compare(index, array[j - 1]) < 0; j--) {
                array[j] = array[j - 1];
            }
            array[j] = index; // insert object at the right point
        }
    }
}

Related Tutorials