Skip to content

Commit bf62ea6

Browse files
committed
Add count_inversions.py
1 parent 4275fe9 commit bf62ea6

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

Python/Count_Inversions.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
def countInversions(nums):
2+
#Our recursive base case, if our list is of size 1 we know there's no inversion and that it's already sorted
3+
if len(nums) == 1: return nums, 0
4+
5+
#We run our function recursively on it's left and right halves
6+
left, leftInversions = countInversions(nums[:len(nums) // 2])
7+
right, rightInversions = countInversions(nums[len(nums) // 2:])
8+
9+
#Initialize our inversions variable to be the number of inversions in each half
10+
inversions = leftInversions + rightInversions
11+
12+
#Initialize a list to hold our sorted result list
13+
sortedNums = []
14+
15+
i = j = 0
16+
#Here we count the inversions that exist between the two halves -- while sorting them at the same time
17+
while i < len(left) and j < len(right):
18+
if left[i] < right[j]:
19+
sortedNums += [left[i]]; i += 1
20+
else:
21+
sortedNums += [right[j]]; j += 1
22+
23+
#Since we know that 'left' is sorted, once we reach an item in 'left' thats bigger than something in right that item and everything to it's right-hand side must be an inversion!
24+
#This line right here is exactly what shrinks the time of this algorithm from n^2 to nlogn as it means we don't need to compare every single pair
25+
inversions += len(left) - i
26+
27+
#Once we've exhausted either left or right, we can just add the other one onto our sortedNums list
28+
sortedNums += left[i:] + right[j:]
29+
30+
return sortedNums, inversions
31+
32+
33+
def main():
34+
nums = [1, 5, 4, 8, 10, 2, 6, 9]
35+
print(countInversions(nums))
36+
37+
main()

0 commit comments

Comments
 (0)