Choose what to sort by
Sort by a rule you pick, and say how to break ties. About 10 minutes.
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.
nums.sort(key=lambda x: abs(x)) # [-1, 1, 2, 3, -3] (3 and -3 tie)
The distances from zero are 3, 1, 3, 2 and 1.
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.
nums.sort(key=lambda x: (abs(x), x)) return nums
Sort by distance from zero, with ties going to the smaller value. What order do you get?
nums = [4, -2, 2, -5]
- A[-2, 2, 4, -5]
- B[-5, -2, 2, 4]
- C[2, -2, 4, -5]
Show the answer
[-2, 2, 4, -5]. −2 and 2 tie, so −2 goes first. Then 4, and −5 is the furthest from zero.
Closest to zero first
Return nums sorted by how far each value is from zero, closest first. If two values are equally far, like −3 and 3, put the smaller one first.
nums = [3, -1, -3, 2, 1] → [-1, 1, 2, -3, 3]
0 ≤ n ≤ 100,000 · −1,000,000,000 ≤ each value ≤ 1,000,000,000