SORT-P3

How far out of order

Practice 3 of 6Sorting6 tests

The problem

A timetable lists trains in the order they are booked to leave. The list a holds the order in which they really left. Count how far out of order it is: the number of inversions, pairs of positions i < j with a[i] > a[j].

count_inversions([2, 4, 1, 3, 5])
# 3: (2, 1), (4, 1), (4, 3)
count_inversions([5, 4, 3, 2, 1])    # 10
count_inversions([2, 2, 1])
# 2: equal values are not out of order

Limits

  • Up to 100,000 values. The answer can be up to about 5 billion; Python’s whole numbers handle that.

Builds on SORT-2 Merge sort.

Continue on a laptop

Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.

Need a hint?0 of 3 opened

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

6 tests, not run yet
Test results
#TestResultReads · time
1A fewNot run
2SortedNot run
3ReversedNot run
4Equal valuesNot run
5Empty and oneNot run
6100,000 valuesNot run