Counts the number of inversions using a naive brute-force algorithm Parameters ---------- arr: arr: array-like, the list containing the items for which the number of inversions is desired. The elements of `arr` must be comparable. Returns ------- num_inversions: The
(arr)
| 10 | |
| 11 | |
| 12 | def count_inversions_bf(arr): |
| 13 | """ |
| 14 | Counts the number of inversions using a naive brute-force algorithm |
| 15 | Parameters |
| 16 | ---------- |
| 17 | arr: arr: array-like, the list containing the items for which the number |
| 18 | of inversions is desired. The elements of `arr` must be comparable. |
| 19 | Returns |
| 20 | ------- |
| 21 | num_inversions: The total number of inversions in `arr` |
| 22 | Examples |
| 23 | --------- |
| 24 | >>> count_inversions_bf([1, 4, 2, 4, 1]) |
| 25 | 4 |
| 26 | >>> count_inversions_bf([1, 1, 2, 4, 4]) |
| 27 | 0 |
| 28 | >>> count_inversions_bf([]) |
| 29 | 0 |
| 30 | """ |
| 31 | |
| 32 | num_inversions = 0 |
| 33 | n = len(arr) |
| 34 | |
| 35 | for i in range(n - 1): |
| 36 | for j in range(i + 1, n): |
| 37 | if arr[i] > arr[j]: |
| 38 | num_inversions += 1 |
| 39 | |
| 40 | return num_inversions |
| 41 | |
| 42 | |
| 43 | def count_inversions_recursive(arr): |