Sort Employees by Rating (Descending)
Given an array ratings of employee performance scores, sort it in descending order (highest rating first) using selection sort. The mechanic is the same as ascending selection sort, but each pass looks for the maximum remaining value instead of the minimum, and swaps it to the front of the unsorted region. Return the sorted array.
Constraints
- 1 ≤ ratings.length ≤ 1000
- 0 ≤ ratingsi ≤ 100
Example
ratings = [72, 95, 68, 88][95, 88, 72, 68]Explanation Each pass finds the largest remaining rating and swaps it to the front: 95, then 88, then 72, leaving 68 in place.
In plain terms
- Descending order
- Each value is less than or equal to the one before it, largest first.
- Comparator
- The rule a sort uses to decide which of two values should come first — flipping the comparison direction flips the whole sort.
Scan for the maximum, then swap it to the front
Scan all 4 ratings — the maximum is 95 at index 1.
What happens in this step
ratings = [72, 95, 68, 88], sortedEnd = 0, max so far = 72 (index 0) idx 1: 95 > 72 → new max = 95 at index 1 idx 2: 68 > 95 → no idx 3: 88 > 95 → no 95 at index 1 beats every other candidate — maxIndex settles on 1.
Steps to visualize
- Set sortedEnd to 0.
- Scan the unsorted region, tracking the index of the largest value seen instead of the smallest.
- Swap that maximum into index sortedEnd.
- Move sortedEnd forward and repeat.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
Scan all 4 ratings — the maximum is 95 at index 1.
What happens in this step
ratings = [72, 95, 68, 88], sortedEnd = 0, max so far = 72 (index 0) idx 1: 95 > 72 → new max = 95 at index 1 idx 2: 68 > 95 → no idx 3: 88 > 95 → no 95 at index 1 beats every other candidate — maxIndex settles on 1.
Solution
function sortRatingsDescending(ratings) {
const arr = ratings.slice();
for (let sortedEnd = 0; sortedEnd < arr.length - 1; sortedEnd++) {
let maxIndex = sortedEnd;
for (let scan = sortedEnd + 1; scan < arr.length; scan++) {
if (arr[scan] > arr[maxIndex]) {
maxIndex = scan;
}
}
if (maxIndex !== sortedEnd) {
const temp = arr[sortedEnd];
arr[sortedEnd] = arr[maxIndex];
arr[maxIndex] = temp;
}
}
return arr;
}- Time
- O(n^2)
- Space
- O(n)
Test cases
| Input | Expected | Covers |
|---|---|---|
ratings = [72, 95, 68, 88] | [95, 88, 72, 68] | example from the docstring |
ratings = [90, 80, 70] | [90, 80, 70] | already in descending order |
ratings = [10, 20, 30, 40] | [40, 30, 20, 10] | fully ascending input needs a complete reversal |
ratings = [50, 50, 80, 50] | [80, 50, 50, 50] | duplicate ratings mixed with a distinct high value |
ratings = [77] | [77] | smallest valid input, a single rating |
ratings = [60, 60, 60] | [60, 60, 60] | every rating is identical |
ratings = [40, 90] | [90, 40] | boundary case, exactly two ratings out of order |