Last active
December 19, 2015 17:19
-
-
Save yanzay/5990591 to your computer and use it in GitHub Desktop.
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
class InversionsCalculator | |
def inversions_count(arr) | |
sort_and_count(arr)[0] | |
end | |
private | |
def sort_and_count(arr) | |
return [0, arr] if arr.length == 1 | |
a, b = split_array(arr) | |
x, a = sort_and_count(a) | |
y, b = sort_and_count(b) | |
z, c = merge_and_count_split(a,b) | |
[x + y + z, c] | |
end | |
def merge_and_count_split(a, b) | |
inversions = i = j = 0 | |
c = [] | |
(a.length + b.length).times do | |
if b[j].nil? || a[i] && a[i] < b[j] | |
c << a[i] | |
i += 1 | |
else | |
c << b[j] | |
j += 1 | |
inversions += a.length - i | |
end | |
end | |
[inversions, c] | |
end | |
def split_array(arr) | |
n = arr.length / 2 | |
[arr[0..n-1], arr[n..-1]] | |
end | |
end | |
calc = InversionsCalculator.new | |
arr = [] | |
File.open('./IntegerArray.txt') do |f| | |
f.each_line{ |line| arr << line.to_i } | |
end | |
puts calc.inversions_count(arr) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment