Created
October 24, 2015 22:04
-
-
Save vtambourine/b9e7fbb06da951a5505f to your computer and use it in GitHub Desktop.
This file contains 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
filename = ARGV.first | |
input_array = File.readlines(filename).map(&:to_i) | |
def merge_sort(array) | |
if array.length <=1 | |
return array, 0 | |
else | |
center = (array.length / 2).floor | |
left, left_inv = merge_sort(array[0..center - 1]) | |
right, right_inv = merge_sort(array[center..array.length]) | |
merged_array, split_inv = merge(left, right) | |
end | |
return merged_array, split_inv + left_inv + right_inv | |
end | |
def merge(left_array, right_array) | |
i = j = inversions = 0 | |
result = [] | |
while (i < left_array.length and j < right_array.length) | |
if left_array[i] < right_array[j] | |
result.push(left_array[i]) | |
i += 1 | |
else | |
inversions += left_array.length - i | |
result.push(right_array[j]) | |
j += 1 | |
end | |
end | |
result += left_array[i..left_array.length] if i < left_array.length | |
result += right_array[j..right_array.length] if j < right_array.length | |
return result, inversions | |
end | |
result = merge_sort(input_array) | |
puts "Sorted array: #{result[0]}" | |
puts "Inversions: #{result[1]}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment