This generic method sorts the input array using an insertion sort and the input Comparator object. - Java Collection Framework

Java examples for Collection Framework:Array Sort

Description

This generic method sorts the input array using an insertion sort and the input Comparator object.

Demo Code


//package com.java2s;

import java.util.Comparator;

public class Main {
    /**/* w w w.ja va  2s  . com*/
     * This generic method sorts the input array using an insertion sort and the input Comparator object.
     * @param arr
     * @param c
     */
    public static <T> void insertionSort(T[] arr, Comparator<? super T> c) {
        // validate parameters
        if (arr == null) {
            throw new IllegalArgumentException(
                    "The given array cannot be null!");
        }
        if (c == null) {
            throw new IllegalArgumentException(
                    "The given comparator cannot be null!");
        }

        T key; // The item to be inserted
        int gapIndex; // Keeps track of the current gap index

        // Go through each item
        for (int i = 1; i < arr.length; i++) {
            // Make the gap
            key = arr[i];
            gapIndex = i;

            // Position the gap
            while (gapIndex > 0 && c.compare(arr[gapIndex - 1], key) > 0) {
                // Move the gap up
                arr[gapIndex] = arr[gapIndex - 1];
                gapIndex--;
            }

            // Insert into the gap
            arr[gapIndex] = key;
        }
    }
}

Related Tutorials