2016-02-07 43 views
0

如果我给这个方法的标题:通用插入排序使用比较对象作为参数?

/** 
* This generic method sorts the input array using an insertion sort and the input Comparator object. 
*/ 
public static <T> void insertionSort(T[] array , Comparator<? super T> comparatorObj){ 

     // Implement method 
} 

在参数的Comparator<? super T> comparatorObj部分,我是想将使得告诉你如何当它在插入排序参数的二手应进行比较的比较对象的方法?

回答

-2

试试这个

public static <T> 
void insertionSortGeneric(T[] a, Comparator<? super T> c) { 
    for (int i=0; i < a.length; i++) { 
    /* Insert a[i] into the sorted sublist */ 
    T v = a[i]; 
    int j; 
    for (j = i - 1; j >= 0; j--) { 
     if (c.compare(a[j], v) <= 0) break; 
     a[j + 1] = a[j]; 
    } 
    a[j + 1] = v; }} 
+0

你根本没有回答OP的问题。 – radoh

+0

在你的代码中使用这个代码它将会有效地使用循环来打印一个。 – Akhil

+0

我在问是否需要创建一个Comparator对象,它告诉如何比较泛型数组中的元素。 – ProjectDefy