We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
N_swaps=0defmerge_sort(arr):n=len(arr)ifn==1:returnarrmed=n//2sub1=merge_sort(arr[:med])sub2=merge_sort(arr[med:])globalN_swapssorted_arr=[]i,j=0,0whilei<len(sub1)andj<len(sub2):ifsub1[i]<=sub2[j]:sorted_arr.append(sub1[i])i+=1elifsub1[i]>sub2[j]:sorted_arr.append(sub2[j])j+=1N_swaps+=len(sub1)-iifi<len(sub1):sorted_arr+=sub1[i:]ifj<len(sub2):sorted_arr+=sub2[j:]returnsorted_arrdefcountInversions(arr):# Write your code hereglobalN_swapsN_swaps=0merge_sort(arr)returnN_swaps
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Merge Sort: Counting Inversions
You are viewing a single comment's thread. Return to all comments →
Python3 My Solution