DEV Community

Discussion on: Selection Sort in Ruby

Collapse
 
mdegoys profile image
Matthieu

Hey Megan,
thanks for keeping up with this series, these sorting algorithms are really interesting.

I'm not sure about the -2, as when I tested with [10, 1, 64, 89, 12, 0] for example, there is one sort missing I think, as it resulted with [0, 1, 10, 12, 89, 64].

Also I guess you could reduce your code a little bit, using for instead of while, and not using smallest_value, as it is related to smallest_index value, which is what you really want here.

def selection_sort(array)
   for index in 0...array.length - 1
    smallest_value_index = smallest_value_index(array, index)
    array[index], array[smallest_value_index] = array[smallest_value_index], array[index]
  end
  array
end

def smallest_value_index(array, from_index)
  smallest_index = from_index
    for index in from_index...array.length
      if array[index] < array[smallest_index]
        smallest_index = index
      end
    end
    smallest_index
end 
Collapse
 
mwong068 profile image
Megan

Hi Matthieu,

I've really started to look forward to your comments because I feel like they are so helpful and are making me a better coder. So thank you, I really appreciate you! And I also appreciate you following with the series too.

I completely agree with your comment on the -2 and have fixed that in my code, thanks for catching that!

Also, I definitely went back and forth on my naming for the smallest_value, so I'm glad you felt the same way haha.

I'll catch you on the next post 😊

Collapse
 
mdegoys profile image
Matthieu

Hey Megan,
I'm glad my comments could help ! I'm looking forward to your next post :)