Skip to content

Instantly share code, notes, and snippets.

@samhavens
Created May 5, 2014 07:04
Show Gist options
  • Save samhavens/cc09d3d654d6bef41d53 to your computer and use it in GitHub Desktop.
Save samhavens/cc09d3d654d6bef41d53 to your computer and use it in GitHub Desktop.
a = []
#the following inputs the test file and puts it into array a when IntegerArray is the input
File.open("IntegerArray.txt").each_line do |line|
a << line.to_i
end
$inversion_count = 0
def merge_sort(array)
return array if array.length == 1
left, right, array = array.shift((array.length/2).round), array, []
left, right = merge_sort(left), merge_sort(right)
while !left.empty? and !right.empty?
if left.first < right.first
array<<left.shift
else
$inversion_count += left.length
array<<right.shift
end
end
array + left + right
end
puts merge_sort(a)
print $inversion_count
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment