Skip to content
CodeItRaw
Sorting

Lesson 3/5

The greatest gift of sorting is this: the values closest to each other end up side by side. "Which two numbers are closest?" needs every pair tried in an unsorted list (n × n); after sorting you look only at neighbours (n).

ordered = sorted(values)
best = ordered[1] - ordered[0]
for i in range(2, len(ordered)):
best = min(best, ordered[i] - ordered[i - 1])
return best
In a sorted list the difference is always "right minus left", so no absolute value is needed. The starting value is a real difference from the list, not a made-up large number.

In a sorted list some answers simply sit at a position: the smallest at the start, the largest at the end, the median in the middle. The largest spread (end to end) does not even need sorting: largest minus smallest is found in one pass.

Tasks

Tasks open in order. Solve them all and the next lesson opens.

This lesson's tasks open when the lessons before it are finished. You can read the explanation now.

  1. 01

    Closest Pair

    Function

  2. 02

    Largest Spread

    Code reading · Break the Code

  3. 03

    Median

    Code reading · Break the Code

If you would rather not wait for the order, every problem is open without locks: Problem list