From 4924445d21223b67241a2cfb0212d6850d56bae3 Mon Sep 17 00:00:00 2001 From: usman-7455 Date: Tue, 29 Apr 2025 21:38:56 +0500 Subject: [PATCH 1/2] Add Count Inversions algorithm using Merge Sort --- sorts/count_inversion.py | 56 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 sorts/count_inversion.py diff --git a/sorts/count_inversion.py b/sorts/count_inversion.py new file mode 100644 index 000000000000..7189a8618ebc --- /dev/null +++ b/sorts/count_inversion.py @@ -0,0 +1,56 @@ +""" +Count Inversions in an array using a modified Merge Sort algorithm. + +An inversion is a pair of indices (i, j) such that: + - i < j + - arr[i] > arr[j] +This represents a disorder in the array relative to a sorted order. + +This implementation efficiently counts the number of such inversions +in O(n log n) time by modifying the merge step of Merge Sort. + +Use Cases: +---------- +- Measuring how far a sequence is from being sorted. +- Evaluating disorder in datasets (e.g., in rankings or sequences). +- Useful in computer vision, bioinformatics, and comparison of lists. +- Core concept in Kendall tau distance and other similarity metrics. +""" +def count_inversions(arr): + def merge_sort(arr): + if len(arr) <= 1: + return arr, 0 + + mid = len(arr) // 2 + left, inv_left = merge_sort(arr[:mid]) + right, inv_right = merge_sort(arr[mid:]) + merged, inv_split = merge(left, right) + + total_inversions = inv_left + inv_right + inv_split + return merged, total_inversions + + def merge(left, right): + i = j = inv_count = 0 + merged = [] + + while i < len(left) and j < len(right): + if left[i] <= right[j]: + merged.append(left[i]) + i += 1 + else: + merged.append(right[j]) + j += 1 + inv_count += len(left) - i # All remaining in left > right[j] + + merged += left[i:] + merged += right[j:] + return merged, inv_count + + _, total_inversions = merge_sort(arr) + return total_inversions + + +# Example usage +if __name__ == "__main__": + sample = [2, 4, 1, 3, 5] + print(f"Inversion count: {count_inversions(sample)}") From f381eacb3052ff4a12752076a0e6f57a16e48a4a Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Tue, 29 Apr 2025 16:40:20 +0000 Subject: [PATCH 2/2] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- sorts/count_inversion.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/sorts/count_inversion.py b/sorts/count_inversion.py index 7189a8618ebc..7713297c1896 100644 --- a/sorts/count_inversion.py +++ b/sorts/count_inversion.py @@ -16,6 +16,8 @@ - Useful in computer vision, bioinformatics, and comparison of lists. - Core concept in Kendall tau distance and other similarity metrics. """ + + def count_inversions(arr): def merge_sort(arr): if len(arr) <= 1: