Created
April 26, 2012 01:50
-
-
Save them0nk/2495136 to your computer and use it in GitHub Desktop.
second smallest number in an array
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
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