public class GenericSort<G extends Comparable> {
private G[] integerarray;
public GenericSort(G[] inputarray){
this.integerarray = inputarray;
//check empty array
if (integerarray ==null || integerarray.length==0){return;}
quickSort(0,integerarray.length-1);
}
public void quickSort(int low, int high){
int i = low;
int j = high;
//set Pivot
G pivot = integerarray[low + (high-low)/2];
while(i<=j){
//check left
while(integerarray[i]<pivot){i++;}
//check right
while(pivot<integerarray[j]){j--;}
//swap
if(i<=j){
G temp = integerarray[i];
integerarray[i] = integerarray[j];
integerarray[j] = temp;
i++;
j--;
}
}
//recursion
if(low<j){quickSort(low,j);}
if(i<high){quickSort(i,high);}
}
}
here the line:
开发者_开发问答while(integerarray[i]<pivot) {
i++;
} &
while(integerarray[i]<pivot){i++;}
is giving error because comarision is not allowed between unknown types. So i extended G from comparable. Still doesnt work. How to solve it?
<
and >
are only for primitives. If your class implements Comparable
, use it's compareTo
method and compare the result to 0
- compareTo
Implementing Comparable does not allow you to use comparison operators >, <, ==. It is not C++, man. :(
Instead you have to use compareTo() method defined in Comparable interface.
And yet another comment. Could you please distinguish between 2 absolutely different things like "does not work" and "does not compile". In your case you cannot compile your code. When your code is not compiled you actually do not have to post so large code snippet. As less text and smaller code snippet you send as higher a chance to get good answer.
Good luck!
PS: check Collections.sort() as a reference. It does exactly what your are trying to implement.
you cant compare objects with operators like <, > or ==.
Comparable is an interface with specifies the method compareTo(Object o)
Look here
精彩评论