此泛型方法使用插入排序和输入比较器对象对输入数组进行排序。
//package com.nowjava; /** 来自 n o w j a v a . c o m**/ import java.util.Comparator; public class Main { /** * 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(// from 时 代 J a v a 公 众 号 - N o w J a v a . c o m "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 &am