Built-in Sort with Custom Comparator - Getting Started / Basic Algorithms

https://algo.monster/problems/custom_comparator_sort

That’s pretty strange what you don’t have any code on C#…

or use cmp_to_key

sorted_tasks = sorted(arr, key=cmp_to_key(lambda t1, t2: t1[1] - t2[1])))

sorted_tasks = [(‘Buy grocery’, 3), (‘Cook dinner’, 5)]

where is ‘arr’ defined? Is this an error?

for c++:

solution.cc: In function ‘void print_sorted_array(std::vector)’:
solution.cc:11:5: error: ‘put_words’ was not declared in this scope
11 | put_words(nums);
| ^~~~~~~~~

Its failed because print and get function are declared after print_sorted_array function it should be before.

c# is added

Something not obvious is that the first Java example is using a Google library called Guava to use Lists.newArrayList that you probably won’t have access to in your interviews.

In order to use this in your code you’d have to add Guava as a dependency and import:
import com.google.common.collect.Lists;

I’m not sure why they used this, but here’s what an alternative with the Java library looks like, they used it before in the previous line:

List<Task> tasks = Arrays.asList(
    new Task("Cook dinner", 5), 
    new Task("Buy grocery", 3)
);
1 Like

The first Java example also won’t compile correctly because it’s calling compareTo() on the priority getter for an int. Updating it to use private Integer priority will fix it:
Collections.sort(tasks, (Task t1, Task t2) -> t1.getPriority().compareTo(t2.getPriority()));

which can then could be shortened in Java 8:

Collections.sort(tasks, Comparator.comparing(Task::getPriority));


Alternatively, you can retain the primitive int priority since Integer allows for nullability and update the comparator:

Comparator<Task> comp = (Task t1, Task t2) -> {
      return Integer.compare(t1.getPriority(), t2.getPriority());
};

This can also be shortened in Java 8 to:
Comparator<Task> comp = Comparator.comparingInt(Task::getPriority); but knowing the previous solution still helpful.

1 Like

Go solution

didn’t take the time to get this working with the set up code (scanner, etc) but works in playground

  1. create a student struct
  2. implement the sort.Interface so that a collection of Student objects can be passed to the various routines in the sort pkg to be sorted by total grade
type Student struct {
	Name         string
	MathGrade    int
	EnglishGrade int
}

func (s Student) String() string {
	return fmt.Sprintf("{%s - M:%d  E:%d}", s.Name, s.MathGrade, s.EnglishGrade)
}

type ByTotalGrade []Student

func (s ByTotalGrade) Len() int { return len(s) }
func (s ByTotalGrade) Less(i, j int) bool { return s[i].MathGrade+s[i].EnglishGrade < s[j].MathGrade+s[j].EnglishGrade }
func (s ByTotalGrade) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
    

func printSortedStudents(students []Student) {
    sort.Sort(ByTotalGrade(students))
    fmt.Println(students)
    sort.Sort(sort.Reverse(ByTotalGrade(students)))
    fmt.Println(students)
}

func splitWords(s string) []string {
    if s == "" {
        return []string{}
    }
    return strings.Split(s, " ")
}