Created
February 15, 2014 04:02
-
-
Save funkotron/9014369 to your computer and use it in GitHub Desktop.
Count inversions in a string using Julia
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
# 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