MCPcopy Index your code
hub / github.com/TheAlgorithms/Python / count_inversions_bf

Function count_inversions_bf

divide_and_conquer/inversions.py:12–40  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

10
11
12def 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
43def count_inversions_recursive(arr):

Callers 1

mainFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected