java如何编写比较器来运行此代码?
我正在尝试运行代码
public void insertionSort(E[] data, Comparator <E> c){
long start = System.nanoTime();
int compare = 0;
int numSwaps = 0;
for (int i = 0; i <data.length; i++){
E tempVal = data[i];
int j = i;
while(j > 0 && c.compare(data[j-1], tempVal) > 0){
data[j] = data[j - 1];
j--;
compare++;
numSwaps++;
}
data[j] = tempVal;
numSwaps++;
}
long stop = System.nanoTime();
long duration = stop - start;
System.out.println("Insertion sort with " + data.length +
" items took " +duration+ " nanoseconds");
}
使用下面的类,但是当我调用intSorter
时似乎出现了问题,因为它与Comparator <E>
不同
import java.util.Comparator;
public class ArraySorterTester {
public static void main(String [] args){
Integer[] test = new Integer[] {4,-2, -3, 5, 1 };
Sorting<Integer> intSorter = new Sorting<Integer>();
intSorter.insertionSort(test, intSorter);
}
}
我真的不明白为什么它不起作用,因为我只是在学习如何使用java。任何帮助都将不胜感激
# 1 楼答案
我试着猜你的分类班:-),它似乎在工作: