Search code examples
javasortingarraylistcomparearr

How comparator works in Java?


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.


Solution

  • 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