views:

244

answers:

4

Right now I have

def min(array,starting,ending)
  minimum = starting
  for i in starting+1 ..ending
    if array[i]<array[minimum]
      minimum = i
    end    
  end

return minimum
end

Is there a better "implementation" in Ruby? This one still looks c-ish. Thanks.

A: 

This is the standard algorithm for finding the minimum element in an array, it can be better by having the array already be sorted before this function is called.

Otherwise I can't find a more efficient way of doing this. Specifically, linear time in big O notation is the best we can do.

AlbertoPL
Im sorry I meant to say Is there a better implementation for the same algorithm in Ruby?
kunjaan
A: 

If this isn't simply an academic question, why not just use Ruby's native sort method? It's implemented using a quicksort algorithm, and is considered to be pretty fast.

a = [3, 4, 5, 1, 7, 5]
a.sort![0] # => 1
Bryan M.
On "large" lists, that's going to be far more expensive. O(n*log(n)) instead of O(n)
sharth
The time increases by a large factor and I cannot integrate the subroutine into another method like Selection_Sort.
kunjaan
Agreed. I was thinking that for some reason a sort had to happen.
Bryan M.
+1  A: 

Basically that's the best you can do, though you can write it a bit more succinctly:

def minval(arr)
    arr.inject {|acc,x| (acc && acc < x ? acc : x)}
end
Paul Betts
I think the OP wanted the index of the minimum value, rather than the value itself. Which makes it a bit harder to use inject.
Matthew Schinckel
And, you don't even need to use anything other than: arr.min to get the minimum value.
Matthew Schinckel
Although this is clever, I cannot use it.
kunjaan
D'oh, misread the question!
Paul Betts
+5  A: 

If you want to find the index of the minimal element, you can use Enumerable#enum_for to get an array of items-index pairs, and find the minimum of those with Enumerable#min (which will also be the minimum of the original array).

% irb
irb> require 'enumerator'
#=> true
irb> array = %w{ the quick brown fox jumped over the lazy dog }
#=> ["the", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog"]
irb> array.enum_for(:each_with_index).min
#=> ["brown", 2]

If you want to bound it to specific array indices:

irb> start = 3
#=> 3
irb> stop = 7
#=> 7
irb> array[start..stop].enum_for(:each_with_index).min
#=> ["fox", 0]
irb> array[start..stop].enum_for(:each_with_index).min.last + start
#=> 3
rampion
WOW. Thats a pretty succint command.
kunjaan
Is there a good tutorial/documentation for enumerator?
kunjaan
http://www.ruby-doc.org/stdlib/libdoc/enumerator/rdoc/index.html
rampion