如何为 运行 这段代码编写一个比较器?

How do I write a comparator to run this code?

我正在尝试 运行 代码

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");
}

下面的 class,但是我调用 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。任何帮助,将不胜感激。

我尝试猜测您的排序 class :-),它似乎有效:

public class Sorting<E extends Comparable<E>> implements Comparator<E> {

    @Override
    public int compare(final E o1, final E o2) {
        return o1.compareTo(o2);
    }

    public void insertionSort(final E[] data, final Comparator<E> c) {

        final long start = System.nanoTime();
        int compare = 0;
        int numSwaps = 0;

        for (int i = 0; i < data.length; i++) {
            final 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++;
        }
        final long stop = System.nanoTime();
        final long duration = stop - start;
        System.out.println("Insertion sort with " + data.length + " items took " + duration + " nanoseconds");
    }
}