如何编写比较器来运行此代码?

时间:2015-01-30 07:30:15

标签: java class

我正在尝试运行代码

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 个答案:

答案 0 :(得分:0)

我试着猜测你的排序类:-),看起来似乎有效:

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