diff --git a/arrays/python/count-inversions.py b/arrays/python/count-inversions.py index 16190435..2bbbc5bd 100644 --- a/arrays/python/count-inversions.py +++ b/arrays/python/count-inversions.py @@ -2,6 +2,8 @@ Algorithm Type: Divide & Conquer Time Complexity: O(n*log(n)) """ +numbers = [8, 2, 1, 5, 7, 3, 9, 2, 0, 1] + def count_split_inv(arr, left, right): split_inv = ridx = lidx = 0 @@ -10,7 +12,7 @@ def count_split_inv(arr, left, right): rsize = len(right) for i in range(size): if lidx != lsize and ridx != rsize: - if right[ridx] <= left[lidx]: + if right[ridx] < left[lidx]: arr[i] = right[ridx] ridx += 1 split_inv += lsize - lidx @@ -23,9 +25,22 @@ def count_split_inv(arr, left, right): elif ridx == rsize: arr[i] = left[lidx] lidx += 1 - return split_inv; + return split_inv -def count_inversions(arr): + +def count_inversions(arr) -> int: + """ + Sort arr and return the number of inversions required. + + >>> numbers + [8, 2, 1, 5, 7, 3, 9, 2, 0, 1] + >>> count_inversions(numbers) + 28 + >>> numbers # numbers has been sorted!! + [0, 1, 1, 2, 2, 3, 5, 7, 8, 9] + >>> count_inversions(numbers) + 0 + """ size = len(arr) if size == 1: return 0 @@ -38,5 +53,5 @@ def count_inversions(arr): return l_inv + r_inv + split_inv -numbers = [8, 2, 1, 5, 7, 3, 9, 2, 0, 1] -print(count_inversions(numbers)) +if __name__ == "__main__": + print(count_inversions(numbers))