user122049 user122049 - 5 days ago 6
Java Question

Cannot call method Java

I tried to write a generic SelectionSort, but there are error suggesting in my

sort()
, I cannot call
findMinIndex(int,int)
or
swap()
though I can call in
main()
. How can I modify my code to rectify this problem?

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


}

Answer

Because you are trying to call a class method on an array. This does not work.

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

result is your generic array. Just call the method directly

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