You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
#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
+
whilei<len(left) andj<len(right):
18
+
ifleft[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
0 commit comments