Aashish Kalia
Aashish Kalia

Reputation: 25

Custom Sorting an array in java using Two values , x and y

I am trying to sort the array based on x values in case x value is same , sort it according to y. After sorting print the values I get an exception, I am calling compare method by overriding compare method of Comparator Interface.

class coder
{
    int x,y,index;
}
public class CoderRating  implements Comparator<coder>{
    public int compare(coder A,coder B)
    {
        if(A.x==B.x)
        {
            if(A.y<B.y)
            return -1;
            else if(A.y>B.y)
            return 1;
            else
            return 0;
        }

        else if(A.x<B.x)
        return -1;

        else
        return 1;
    }

    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
        coder []c=new coder[n];

        for(int i=0;i<n;i++)
        {
            c[i]=new coder();
            c[i].x=sc.nextInt();
            c[i].y=sc.nextInt();
            c[i].index=i;
        }
        Arrays.sort(c);
        for(int i=0;i<n;i++)
        {
            System.out.println(c[i].x + "  "+c[i].y );
        }
    }

}

Upvotes: 1

Views: 175

Answers (3)

Priya Jain
Priya Jain

Reputation: 830

You are calling the Arrays.sort on coder object and not passing any comparator object so Arrays.sort is looking for comparable in Coder class. 2 solutions to your problem:

  1. change: Pass the comparator which you want while sorting coder array. Change Arrays.sort(c) to Arrays.sort(c,new CoderRating());

  2. implement comparable in coder. Override the compareTo method and move the code of compare method inside CoderRating to the compareTo method in Coder.

PS: For your code cleanup :

Change:

       `if(A.y<B.y)
            return -1;
        else if(A.y>B.y)
            return 1;
        else
            return 0;`

can be changed to one liner:

return Integer.compare(A.y, B.y);

Output:

3 1 2 2 3 2 1 1 2 2 1 2 3

Upvotes: 0

Allan
Allan

Reputation: 12448

You are not calling the sorting algorithm with the Comparator you have implemented:

Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
coder []c=new coder[10];

for(int i=0;i<n;i++)
{
    c[i]=new coder();
    c[i].x=sc.nextInt();
    c[i].y=sc.nextInt();
    c[i].index=i;
}
Arrays.sort(c, new CoderRating()); //this is how it should be called
for(int i=0;i<n;i++)
{
    System.out.println(c[i].x + "  "+c[i].y );
}

output:

enter image description here

Upvotes: 0

Ousmane D.
Ousmane D.

Reputation: 56453

You're calling the wrong overload of sort, it should be:

Arrays.sort(c, new CoderRating());

Currently, you're calling this sort method instead of this, specifying your comparator hence the issue.

Upvotes: 1

Related Questions