-2

how comparetor works in java ?

import java.util.*;
public class S {
    static Scanner sc = new Scanner(System.in);
    static Integer a[] = new Integer[3];

    public static void main(String[] args) {
        int t = sc.nextInt();
        while (t-- > 0) {
            int n=3;
            for (int i = 0; i < n; i++) {
                a[i] = sc.nextInt();
            }
            Arrays.sort(a,new Sort1());
        }
    }
}
class Sort1 implements Comparator<Integer>
{
    public int compare(Integer a,Integer b)

    {
        for(int a1:S.a){
            System.out.print(a1+" ");
        }
        System.out.println();
        // return a-b;
        return 1;
    }
}

Input:

1
5 2 7

output

5 2 7

why output is not 7 5 2?

what am I think if we return 1 than.

1.5
2.5 2(becuse of one return)=>2 5
3.7 2 5=>7 5 2

In brief I am curious about how internal values are compare and sorting is done.

1 Answers1

1

So your understanding about Comparator is wrong.

From the name itself we can assume that it needs to compare something right? but in your code you are not comparing anything but you are printing the values in comparator which is wrong.

If you check the arguments of the comparator you can see two integers are passing to it. Those integers are actually your array elements. You need to compare those elemets.

public int compare(Integer a,Integer b)
    {
        if(a < b){
            return 1;
        }else if( a == b){
            return 0;
        }
        else {
            return -1;

        }
    }

Like this and print your array in main. It will be sorted

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Anoop LL
  • 1,548
  • 2
  • 21
  • 32
  • 1
    Good. You can reduce that down to a one-liner: `return Integer.compare( a , b ) ;` – Basil Bourque Jan 06 '21 at 06:17
  • Be careful on your use of the triple-backtick formatting of example code. You need the opening ticks to be on their own line with first line of code *below* that. And you need to always include the ending ticks. If omitted, that messes up things to follow such as links. I fixed both these problems in your Answer here. – Basil Bourque Jan 06 '21 at 06:43