Skip to content

Instantly share code, notes, and snippets.

@them0nk
Created March 15, 2012 01:49
Show Gist options
  • Save them0nk/2041148 to your computer and use it in GitHub Desktop.
Save them0nk/2041148 to your computer and use it in GitHub Desktop.
Method to count the number of inversion in an array of numbers
def count_inversion arr
def count_and_merge arr1, arr2
arr = []
j = 0
i = 0
count = 0
while (i != arr1.size) && (j != arr2.size)
if arr1[i] < arr2[j]
arr << arr1[i]
i = i+1
elsif arr1[i] == arr2[j]
while arr1[i] == arr2[j]
arr << arr1[i]
i = i+1
end
arr << arr2[j]
j = j+1
count = count + arr1.size - i
else
arr << arr2[j]
j = j+1
count = count + arr1.size - i
end
end
if i == arr1.size
arr2[j..-1].each { |m| arr << m }
end
if j == arr2.size
arr1[i..-1].each { |m| arr << m }
end
return arr,count
end
if arr.size > 2
arr1,count1 = count_inversion arr[0..arr.size/2]
arr2,count2 = count_inversion arr[arr.size/2+1..-1]
arr3,count3 = count_and_merge(arr1,arr2)
return arr3,count1+count2+count3
else
count = 0
return arr,0 if arr.size == 1
if arr[0] > arr[1]
arr[0], arr[1] = arr[1], arr[0]
count = 1
end
return arr,count
end
end
def count_inversion arr
temp_array = Array(arr.size)
inv_count = 0
blksize = 1
while true do
blksize = 2*blksize
(0..arr.size-1).step(blksize) do |m|
#merge two partial blks
blk1start = m
blk1count = blksize/2 if arr.size >= blk1start + blksize/2
blk1count = arr.size - blk1start if arr.size < blk1start + blksize/2
blk1end = blk1start + blk1count - 1
blk2start = blk1start + blk1count
blk2count = blksize/2 if arr.size >= blk2start + blksize/2
blk2count = arr.size - blk2start if arr.size < blk2start + blksize/2
blk2end = blk2start + blk2count - 1
# copy first half into new temp array if required
if blk2count != 0
next if arr[blk1end] < arr[blk2start]
j = 0
(blk1start..blk1end).each { |m| temp_array[j] = arr[m]; j += 1 }
end
next if blk2count == 0
# compare and save
tempcount = j
j = 0
k = 0
index = blk1start
while (j < tempcount) and (k < blk2count)
if (temp_array[j] <= arr[blk2start + k])
arr[index] = temp_array[j]
j += 1
index += 1
elsif (temp_array[j] > arr[blk2start + k])
arr[index] = arr[blk2start + k]
k += 1
index += 1
inv_count += (tempcount - j)
end
end
# if (j == tempcount)
# while (k != blk2count)
# arr[index] = arr[blk2start + k]
# k += 1
# index += 1
# end
# end
if (k == blk2count)
while (j != tempcount)
arr[index] = temp_array[j]
j += 1
index += 1
end
end
end
break if blksize > arr.size
end
return arr,inv_count
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment