Skip to content

Instantly share code, notes, and snippets.

@theHamdiz
Last active June 12, 2017 07:06
Show Gist options
  • Save theHamdiz/9dcd780fe79ce1f715e753fcac3b5cdb to your computer and use it in GitHub Desktop.
Save theHamdiz/9dcd780fe79ce1f715e753fcac3b5cdb to your computer and use it in GitHub Desktop.
Best way to perform selection sorting in ruby, a not so recommended algorithm for large sets of data.
require_relative 'random_password'
include RandomPassword
class Array
def selection_sort
start_time = Time.now
# Selection sort (very slow on large lists)
a = self
# get the number of indices in the array
n = a.size - 1
# for the number of items in the array - 1 do this
n.times do |i|
# consider this index value the current minimum, store it in a variable
index_min = i
# start from the element with the next index and compare the whole array using the upto(array_length) method
(i + 1).upto(n) do |j|
# j is the second counter ( you can't use i twice, we're in a double loop )
# change the index_min if the next element is lesser than the current_element, to indicate that next element
index_min = j if a[j] < a[index_min]
end
# swap the values of the two indices [ to spare some needless objects ]
a[i], a[index_min] = a[index_min], a[i] if index_min != i
end
puts "It took selection sort #{Time.now - start_time} ms for a 256 membered array"
self
end
end
# now we're talking... :D
puts generate.split('').selection_sort.inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment