Skip to content

Instantly share code, notes, and snippets.

@somebody32
Created February 3, 2013 14:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save somebody32/4702066 to your computer and use it in GitHub Desktop.
Save somebody32/4702066 to your computer and use it in GitHub Desktop.
merge and count inversions in array
def sort_and_count(list)
return [0, list] if list.size <= 1
mid = list.size / 2
left = list[0, mid]
right = list[mid, list.size-mid]
left_result = sort_and_count(left)
right_result = sort_and_count(right)
merge_result = merge_and_count(left_result[1], right_result[1])
[left_result[0] + right_result[0] + merge_result[0], merge_result[1]]
end
def merge_and_count(left, right)
inversions = 0
sorted = []
until left.empty? || right.empty?
if left.first <= right.first
sorted << left.shift
else
sorted << right.shift
inversions += left.size
end
end
sorted.concat(right).concat(left)
[inversions, sorted]
end
result = sort_and_count []
puts "number of inverstions: #{result[0]}"
puts "ordered array: #{result[1]}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment