Skip to content

Instantly share code, notes, and snippets.

@woodRock
Created September 22, 2018 04:59
Show Gist options
  • Save woodRock/38ef9018dc3382f110a9e57517cb7606 to your computer and use it in GitHub Desktop.
Save woodRock/38ef9018dc3382f110a9e57517cb7606 to your computer and use it in GitHub Desktop.
We can determine how "out of order" an array A is by counting the number of inversions it has. Two elements A[i] and A[j] form an inversion if A[i] > A[j] but i < j. That is, a smaller element appears after a larger element. Given an array, count the number of inversions it has. Do this faster than O(N^2) time. You may assume each element in the…
#!/usr/bin/env ruby
def out_of_order set
n = set.size()
inv = 0
n.times do |i|
(i+1...n).each do |j|
inv += 1 if set[i] > set[j]
end
end
return inv
end
set = [5, 4, 3, 2, 1]
puts out_of_order set
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment