有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

  1. # 1 楼答案

    我试着猜你的分类班:-),它似乎在工作:

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