Last active
December 17, 2015 10:49
-
-
Save ryaninhust/5597802 to your computer and use it in GitHub Desktop.
Find inversions in Array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def merge_array(l_array, r_array): | |
merged_array = [] | |
i, j = 0, 0 | |
local_count = 0 | |
while(i < len(l_array) and j < len(r_array)): | |
if l_array[i] > r_array[j]: | |
merged_array.append(r_array[j]) | |
local_count += len(l_array) - i | |
j += 1 | |
else: | |
merged_array.append(l_array[i]) | |
i += 1 | |
tail_array = l_array[i:] if i < len(l_array) else r_array[j:] | |
return merged_array+tail_array, local_count | |
def find_inversions_count(input_array, a): | |
if len(input_array) > 1: | |
l_array, l_count = find_inversions_count( | |
input_array[:(len(input_array)+1)/2], a) | |
r_array, r_count = find_inversions_count( | |
input_array[(len(input_array)+1)/2:], a) | |
merged_array, local_count = merge_array( | |
l_array, r_array) | |
a.append(local_count) | |
return merged_array, a | |
else: | |
return input_array, 0 | |
if __name__ == "__main__": | |
input_array = [6, 5, 4, 3, 2, 1] | |
assert sum(find_inversions_count(input_array, [])[1]) == 15 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment