Reputation: 755
I'm going by this algorithm to solve the problem:
Initialize both first and second smallest as INT_MAX
.
first = second = INT_MAX
Loop through all the elements. a. If the current element is smaller than the first, then update the first and the second. b. Else if the current element is smaller than the second, then update the second.
Here's my code:
#finds second smallest element's index in list
def secondSmallest(list)
first = FIXNUM_MAX
second = FIXNUM_MAX
list.each_with_index do |item, index|
if item < first
second = first
first = index
elsif item < second
second = index
end
end
return second
end
I do not get the output I expect. I don't know where I'm going wrong.
Upvotes: 0
Views: 181
Reputation: 3175
Well I think you can do this in a single line with the help of ruby iterators
list.index(list.sort.second)
Upvotes: 1
Reputation: 504
You are storing the indexes in first and second. Thus you cannot use them for value comparisons : item < second
I think what you would need is 4 variables : maxVal, maxValIndex, minVal, minValIndex if you are going to follow the above mentioned approach.
Upvotes: 3