2016-02-07 42 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