DSA Factory
Free lessonsSorting · Stage 0 · Sort it first · Step 3

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.

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
Quick check

Sort by distance from zero, with ties going to the smaller value. What order do you get?

nums = [4, -2, 2, -5]
  1. A[-2, 2, 4, -5]
  2. B[-5, -2, 2, 4]
  3. 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.

Your problem

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.

Example
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

Solve it in your browserPython, C++, Java or JavaScript. Hints if you get stuck. No sign-up needed.
Start coding