Sorting: Comparator

Sort by

recency

|

501 Discussions

|

  • + 0 comments

    Javascipt

    function processData(input) {
        //Enter your code here
        const arr = input.split("\n")
        const result = []
        for (let i = 1; i < arr.length; i++) {
            result.push(arr[i].split(" "))
        }
        result.sort((a, b) => {
            return b[1] - a[1];
        });
    
        result.sort((a, b) => {
            if (b[1] === a[1] && b[0] > a[0]) {
                return -1;
            }
        });
        console.log(result.join("\n").replaceAll(",", " "));
    
    }
    
  • + 0 comments

    if you are working on java 15.

    import java.io.; import java.util.;

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

        checker[] arr=new checker[n];
        for(int i=0;i<n;i++){
            String name=sc.next();
            int no=sc.nextInt();
            arr[i]=new checker(name,no);
        }
        compare(arr);
    
        for(int i=0;i<arr.length;i++){
            System.out.println(arr[i].name +" "+ arr[i].no);
        }
    }
    
    public static void compare(checker[] arr){
        Arrays.sort(arr,(o1,o2) -> {
            int nocompar=Integer.compare(o2.no, o1.no);
            if(nocompar == 0){
                return o1.name.compareTo(o2.name);
            }
            return nocompar;
        });
    }
    

    }

    class checker{ String name; int no;

    checker(String name,int no){
        this.name=name;
        this.no=no;
    }
    

    }

  • + 0 comments
    class Player:
        def __init__(self, name, score):
            self.name = name
            self.score = score
            
        def __repr__(self):
            return self.name,self.score
            
        def comparator(a, b):
            if a.score == b.score and a.name == b.name:
                return 0
            if a.score > b.score:
                return -1
            elif b.score > a.score:
                return 1
            if a.name < b.name:
                return -1
            return 1
    
  • + 0 comments

    Java Solution with Checker class

    class Checker implements Comparator {

    @Override
    public int compare(Player p1, Player p2){
        if (p1.score == p2.score){
            return p1.name.compareTo(p2.name);
        } else {
            return p2.score - p1.score;
        }
    }
    

    }

  • + 0 comments

    Java Solution

    if( (a.score) == (b.score) ){
    	return (a.name).compareTo(b.name);
    }
    	return (b.score) - (a.score);