Is there a better way to find the location of the minimum element in an array?

I have now

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.

+3
source share
5 answers

If you want to find the index of the minimum element, you can use Enumerable#enum_forto get an array of pairs of index elements and find the minimum of them with Enumerable#min(which will also be minimal for 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 associate it with 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
+6
source

Basically, what you can best do, although you can write it a little more briefly:

def minval(arr)
    arr.inject {|acc,x| (acc && acc < x ? acc : x)}
end
+1
source

, ruby ​​1.9.2:

a = [6, 9, 5, 3, 0, 6]
a.find_index a.min
+1

, , .

Otherwise, I cannot find a more efficient way to do this. In particular, the best time we can make is linear time in large notation.

0
source

If this is not just an academic question, why not just use the Ruby native method sort? It is implemented using a quick sort algorithm and is considered pretty fast.

a = [3, 4, 5, 1, 7, 5]
a.sort![0] # => 1
-1
source

Source: https://habr.com/ru/post/1708233/


All Articles