Created
August 26, 2016 03:12
-
-
Save tylerjohnst/e77c904f9377ac01d9b97270214e2315 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def insertion_sort(collection) | |
collection.count.times do |i| | |
index = i | |
next if index.zero? | |
right_value = collection[i] | |
while index > 0 | |
index -= 1 | |
left_value = collection[index] | |
if right_value < left_value | |
collection[index] = right_value | |
collection[i] = left_value | |
next | |
end | |
end | |
end | |
collection | |
end | |
def selection_sort(source_collection) | |
new_collection = [source_collection.first] | |
source_collection.each.with_index do |number, index| | |
next if index.zero? | |
didInsert = false | |
new_collection.each.with_index do |new_collection_number, i| | |
if number <= new_collection_number | |
new_collection.insert(i, number) | |
didInsert = true | |
break | |
end | |
end | |
new_collection.push(number) unless didInsert | |
end | |
return new_collection | |
end | |
def bubble_sort(collection) | |
isUnsorted = true | |
while isUnsorted | |
isUnsorted = false | |
collection.count.times do |i| | |
left_value = collection[i] | |
right_value = collection[i + 1] | |
if left_value && right_value && left_value > right_value | |
collection[i] = right_value | |
collection[i + 1] = left_value | |
isUnsorted = true | |
end | |
end | |
end | |
collection | |
end | |
if __FILE__ == $0 | |
require 'minitest/spec' | |
require 'minitest/autorun' | |
describe 'algorithms' do | |
let(:collection) { 1000.times.map { rand(1000) } } | |
describe "insertion_sort" do | |
it 'correctly sorts' do | |
insertion_sort(collection).must_equal collection.sort | |
end | |
end | |
describe "bubble_sort" do | |
it 'correctly sorts' do | |
bubble_sort(collection).must_equal collection.sort | |
end | |
end | |
describe "seleciton_sort" do | |
it 'correctly sorts' do | |
selection_sort(collection).must_equal collection.sort | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment