Gopal
Gopal

Reputation: 745

Generic Sort- comparision problem

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?

Upvotes: 0

Views: 215

Answers (3)

Sibbo
Sibbo

Reputation: 3914

you cant compare objects with operators like <, > or ==.
Comparable is an interface with specifies the method compareTo(Object o)
Look here

Upvotes: 2

AlexR
AlexR

Reputation: 115378

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.

Upvotes: 2

unbeli
unbeli

Reputation: 30248

< and > are only for primitives. If your class implements Comparable, use it's compareTo method and compare the result to 0

Upvotes: 4

Related Questions