Skip to content

Instantly share code, notes, and snippets.

@funkotron
Created February 15, 2014 04:02
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 funkotron/9014369 to your computer and use it in GitHub Desktop.
Save funkotron/9014369 to your computer and use it in GitHub Desktop.
Count inversions in a string using Julia
# Julia program to count number of inversions in a string
# using properties of the MergeSort algorithm
global inversions = 0
function arrange(xs, ys)
result = Int64[]
while (length(xs) > 0) & (length(ys) > 0)
if xs[1]<=ys[1]
push!(result,shift!(xs))
else
push!(result,shift!(ys))
global inversions+=length(xs)
end
end
if length(xs) > 0
append!(result, xs)
else
append!(result, ys)
end
return result
end
function merge_sort(xs)
len = length(xs)
if len == 1
return xs
end
half=int(floor(len/2))
lhalf=xs[1:half]
rhalf=xs[half+1:end]
return arrange(merge_sort(lhalf), merge_sort(rhalf))
end
function second_highest(xs, is_last=true)
len=length(xs)
if len == 1
return xs
end
half=int(floor(len/2))
lhalf=xs[1:half]
rhalf=xs[half+1:end]
lval = second_highest(lhalf,false)
rval = second_highest(rhalf,false)
if is_last
return min(lval,rval)
else
return max(lval,rval)
end
end
in = readdlm("IntegerArray.txt",'\n')
# println(size(in))
# x=merge_sort(in)
# println(x)
# println([1,2,3,4,5])
# x= merge_sort([1,2,3,4,5])
# x= merge_sort([1,3,5,2,4,6])
# println(x)
# println(inversions)
println(second_highest([1,2,3,9,3,4,10,8,7,6]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment