Skip to content

Instantly share code, notes, and snippets.

@brianstorti
Created May 3, 2011 13:19
Show Gist options
  • Save brianstorti/953310 to your computer and use it in GitHub Desktop.
Save brianstorti/953310 to your computer and use it in GitHub Desktop.
Selection Sort in ruby
# Selection sort (very slow on large lists)
a = [9,8,6,1,2,5,4,3,9,50,12,11]
n = a.size - 1
n.times do |i|
index_min = i
(i + 1).upto(n) do |j|
index_min = j if a[j] < a[index_min]
end
# Yep, in ruby I can do that, no aux variable. w00t!
a[i], a[index_min] = a[index_min], a[i] if index_min != i
end
@py4ina
Copy link

py4ina commented Dec 27, 2016

nice)

@radoAngelov
Copy link

radoAngelov commented Mar 16, 2017

This is my solution. It is a way more elegant maybe :)

`def selection_sort(array)

n = array.size - 1

n.times do |i|
	(i + 1).upto(n) { |j| array[i], array[j] = array[j], array[i] if array[i] > array[j] }
end

array

end`

@neo4u
Copy link

neo4u commented Jul 27, 2017

Is the if index_min != i needed at the end? Cuz if == index_min then you just swap it with itself so it will work even without that condition.

def selection_sort(data)
  n = data.count
  0.upto(n - 1) do |i|
    min_idx = i
    (i + 1).upto(n - 1) { |j| min_idx = j if data[j] < data[min_idx] }
    data[i], data[min_idx] = data[min_idx], data[i] # unless min.eql?(i)
  end
end

@bestwebua
Copy link

bestwebua commented Sep 13, 2017

My ruby version of selection sort:

def selection_sort(arr)
  (arr.size-1).times do |index|
    tmp_item, tmp_index = arr[index], index
      for i in index...arr.size
        tmp_item, tmp_index = arr[i], i if arr[i] < tmp_item
      end
    arr[index], arr[tmp_index] = arr[tmp_index], arr[index]
  end
  arr
end

@jishemaryo
Copy link

great

@DanielAmah
Copy link

DanielAmah commented May 27, 2019

def selection_sort(arr)
  n = arr.length - 1
  n.times do |i|
    min_index = i
    ((i + 1)..n).each do |j|
      min_index = j if arr[j] < arr[min_index]
    end
    arr[i], arr[min_index] = arr[min_index], arr[i] if min_index != i
  end
  arr
end

arr = [2, 5, 6, 2, 5425, 54, 5, 4, 12, 7, 3, 5, 5]
print selection_sort(arr)

@RicoVendritto
Copy link

Love it!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment