无法调用Java方法

时间:2016-11-30 13:38:47

标签: java

我尝试编写一个通用的SelectionSort,但我的sort()中有错误提示,虽然我可以拨打findMinIndex(int,int),但我无法拨打swap()main()。如何修改代码以纠正此问题?

public class SelectionSort<T extends Comparable<T>>{
 T[] result = null;
static int size = 0;
SelectionSort(T[] a){
    result = a;
    size = a.length;
}
public int findMinIndex(int begin, int end){
    T min = result[begin];
    int index = begin;
    while(begin<=end){
        if(result[begin].compareTo(min)<0){
            min = result[begin];
            index = begin;
        }
        begin++;
    }
    return index;
}
public void swap(int i, int j){
    T temp = result[i];
    result[i]=result[j];
    result[j]=temp;
}
private int getSize(){
    return size;
}

public  void sort(){
    int have_sorted_till = -1;
    int index = -1;
    while(have_sorted_till<size){
        index = result.findMinIndex(have_sorted_till+1,size-1);
        result.swap(index, have_sorted_till+1);
        have_sorted_till++;
    }
}

public String toString(){
    String s = "";
    for(int i=0; i<size; i++){
        s = s + result[i]+",";
    }
    return s;
}

public static void main(String[] args){
    Double[] a =  new Double[]{2.2,5.7,2.8,9.7,3.9,12.3};
    SelectionSort<Double> b = new SelectionSort<Double>(a);
    b.swap(0,5);
        System.out.print(b.toString());
}

}

1 个答案:

答案 0 :(得分:2)

因为您尝试在数组上调用类方法。这不起作用。

    index = result.findMinIndex(have_sorted_till+1,size-1);
    result.swap(index, have_sorted_till+1);

result是您的通用数组。只需直接调用该方法

    index = findMinIndex(have_sorted_till+1,size-1);
    swap(index, have_sorted_till+1);