We've all come across various sorting algorithms like bubble sort, merge sort etc whether being new or experienced in programming but sometimes the default sorting is not enough & requires a little tune up, then you need to implement a custom comparison.
This post explores a fundamental property of comparator functions. You'll encounter it whenever you write a custom comparator in JavaScript, especially after discovering that Array.prototype.sort() sorts values lexicographically by default or while solving coding problems on LeetCode for priority queues.
For instance,
//lexicographic comparison converts the values to strings and
then compares
[10, 2, 5].sort();
// [10, 2, 5]
//comparator here uses numerical value
[10, 2, 5].sort((a, b) => a - b);
// [2, 5, 10]
The Rule Every Comparator Follows
This is mainly about the underlying comparison principle used when comparing two values and deciding which one to place first and which one to place later.
The comparator decides the relative placement of two values, by
- using a 'a certain custom comparison logic' and
- communicating that ordering by returning a negative number, zero, or a positive number.
A comparator returns:
- a negative value if a should come before b
- zero if they are considered equal
- positive value if a should come after b
Sorting algorithms do not generally subtract values. However,
Using a - b is simply a convenient implementation for numbers because subtraction naturally produces the required sign.
For an array of objects:
[
{ age: 54, height: 173 },
{ age: 23, height: 180 }
]
Comparison based on age
(a, b) => {
if (a.age < b.age) return -1;
if (a.age > b.age) return 1;
return 0;
}
Comparison based on height
(a, b) => {
if (a.height < b.height) return -1;
if (a.height > b.height) return 1;
return 0;
}
However, the above comparison can be done like this as well:
(a, b) => a.height - b.height;
This works because if a.height < b.height, the subtraction produces a negative result,
indicating that a should be placed before b.
Likewise, a positive result places a **after** b, and
0 means the two values are considered equal for sorting purposes.
Top comments (0)