I always return 1 in Compare to, but i do not find ans [closed] Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of I always return 1 in Compare to, but i do not find ans [closed] without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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;
    }
}

hi can solve my problem. how compare tor work in java? Input: 1 5 2 7 output 5 2 7 why out put is not 7 5 2? what i thin if we return 1 than. 1.5 2.5 2(becuse of one return)=>2 5 3.7 2 5=>7 5 2

Answer

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

We are here to answer your question about I always return 1 in Compare to, but i do not find ans [closed] - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji