Advanced · Sorting algorithms · 171 of 264
Counting inversions
An inversion is a pair of positions i < j with a[i] > a[j]. Count them quickly with merge sort: lists can have up to 1000 numbers.
Input: n, then n whole numbers on one line. Output: the number of inversions.
Examples
Input
5 2 4 1 3 5
Output
3
Input
3 1 2 3
Output
0
Input
4 4 3 2 1
Output
6
One more test checks other inputs when you press Check.
Stuck? The idea behind sorting algorithms
Bubble sort swaps neighbours that are in the wrong order, pass after pass. Insertion sort takes each item in turn and slides it back into place among those before it. Merge sort splits the list, sorts each half and merges them.
These exercises ask for the steps, not just the result: write the algorithm yourself rather than calling sorted().
a = [5, 1, 4, 2]
for end in range(len(a) - 1, 0, -1):
for i in range(end):
if a[i] > a[i + 1]:
a[i], a[i + 1] = a[i + 1], a[i]
print(a)Watch for: Off-by-one: comparing a[i] with a[i + 1] means i must stop one before the end.