Created
October 4, 2019 05:37
-
-
Save sanchojaf/bd7ba6b77f499bdc3ff8635166fa3ced to your computer and use it in GitHub Desktop.
ruby insertion sort
This file contains hidden or 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
# insertion sort | |
class Sequence | |
attr_accessor :values, :size | |
def initialize(array) | |
@values = array | |
@size = array.length | |
end | |
def sort | |
result = values.dup | |
values.each_with_index do |item, i| | |
j = i | |
while j > 0 && result[j - 1] > item | |
result[j] = result[j - 1] | |
j -= 1 | |
end | |
result[j] = item | |
end | |
result | |
end | |
end | |
require 'rspec/autorun' | |
RSpec.describe Sequence do | |
let(:org_array) do | |
[2,5,6,7] | |
end | |
it 'if sorted return sorted' do | |
seq = Sequence.new(org_array) | |
expect(seq.sort).to eq org_array | |
end | |
it 'if inverse sorted return sorted' do | |
seq = Sequence.new(org_array.reverse) | |
expect(seq.sort).to eq org_array | |
end | |
it 'if unsorted return sorted' do | |
seq = Sequence.new([5,2,7,6]) | |
expect(seq.sort).to eq [2,5,6,7] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment