Exit
  1. Learn
  2. Check
  3. Solve
  4. Reflect

Sort by a key

Smallest first isn't always the order you want. Imagine sorting houses by how far they are from the station instead of by house number. You tell the sort what to look at: a key.

To order numbers by distance from zero, the key is the absolute value, so −1 comes before 2 and 2 comes before −3.

Python: takes a key function.
C++, Java and JavaScript: take a compare function that says which of two values goes first.
In code
nums.sort(key=lambda x: abs(x))
# [-1, 1, 2, 3, -3]  (3 and -3 tie)
Sorting [3, -1, -3, 2, 1] by distance from zero
3
0
-1
1
-3
2
2
3
1
4
i

The distances from zero are 3, 1, 3, 2 and 1.

Move 1 of 4

Always settle ties

−3 and 3 are the same distance from zero. Without a rule, either could come first, and your answer might not match the expected one. Two houses the same distance from the station need a second rule, say the lower house number first.

Add a second key that only counts when the first is equal. Here: the smaller value first.

Compare distances first. Only if they are equal, compare the values.
Java: primitive int arrays can't take a compare function, so copy into a list of Integer first.
In code
nums.sort(key=lambda x: (abs(x), x))
return nums