Skip to content

Instantly share code, notes, and snippets.

@jayrobin
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jayrobin/9607954 to your computer and use it in GitHub Desktop.
Save jayrobin/9607954 to your computer and use it in GitHub Desktop.
A selection of basic sorting algorithms in Ruby
module SortAlgorithms
def self.benchmark(iterations, method, array)
start_time = Time.now
iterations.times { |i| method.call(array.clone) }
Time.now - start_time
end
def self.bubble_sort(array)
array.each do |elem|
(array.size - 1).times do |i|
if array[i] > array[i + 1]
array[i], array[i + 1] = array[i + 1], array[i]
end
end
end
end
def self.selection_sort(array)
(array.size - 1).times do |i|
min = i
(array.size - i).times do |j|
min = i + j if array[i + j] < array[min]
end
array[i], array[min] = array[min], array[i]
end
array
end
def self.merge_sort(array)
return array if array.size <= 1
left = merge_sort(array[0...array.size / 2])
right = merge_sort(array[array.size / 2...array.size])
merge(left, right)
end
def self.quick_sort(array)
return array if array.size <= 1
pivot = array.sample
left_partition = quick_sort(array.find_all { |x| x < pivot })
right_partition = quick_sort(array.find_all { |x| x > pivot })
left_partition + [pivot] + right_partition
end
private
def self.merge(left, right)
array = []
until left.empty? || right.empty?
array << if left[0] < right[0]
left.shift
else
right.shift
end
end
array + left + right
end
end
ARRAY_SIZE = 10
random_array = ARRAY_SIZE.times.map { |i| rand(1000) }
best_array = (1..ARRAY_SIZE).to_a
worst_array = best_array.reverse
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment