Skip to content

Instantly share code, notes, and snippets.

@them0nk
Created April 26, 2012 01:50
Show Gist options
  • Save them0nk/2495136 to your computer and use it in GitHub Desktop.
Save them0nk/2495136 to your computer and use it in GitHub Desktop.
second smallest number in an array
def second_smallest arr
min_arr = []
arr.each_slice(2) do |x,y|
if y.nil? or x < y
min_arr << x
else
min_arr << y
end
end
if min_arr.size > 2
sec_min,min = second_smallest(min_arr)
min_ind = min_arr.index(min)
if min_ind % 2 == 0
if !min_arr[min_ind+1].nil? and sec_min > min_arr[min_ind+1]
sec_min = min_arr[min_ind+1]
end
else
if sec_min > min_arr[min_ind-1]
sec_min = min_arr[min_ind-1]
end
end
return sec_min, min
else
if min_arr[0] < min_arr[1]
return min_arr[1],min_arr[0]
else
return min_arr[0],min_arr[1]
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment