Last active
December 7, 2021 14:28
-
-
Save RyanSnodgrass/c96248428d6851bf6ce44d552f2b21ed to your computer and use it in GitHub Desktop.
Practice by implementing bubble sort in Ruby
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
require 'byebug' | |
require 'rspec' | |
class BubbleSort | |
attr_reader :arr | |
def initialize(input) | |
@arr = input | |
end | |
def bubble_bubble | |
return if @arr.size <= 1 | |
loop do | |
bubble_up | |
return if @stop_flag | |
end | |
end | |
def bubble_up | |
@stop_flag = true | |
@arr.each_with_index do |element, index| | |
return if index == @arr.size - 1 | |
if element > @arr[index + 1] | |
@stop_flag = false | |
@arr.delete_at(index) | |
@arr.insert(index + 1, element) | |
end | |
end | |
end | |
end | |
RSpec.describe 'Bubble sort' do | |
it 'sorts first pass' do | |
a = [3, 2, 1] | |
@b = BubbleSort.new(a) | |
@b.bubble_up() | |
expect(@b.instance_variable_get(:@stop_flag)).to eq(false) | |
expect(@b.arr).to eq([2, 1, 3]) | |
end | |
it 'sets continue to false when all sorted' do | |
a = [1, 2, 3] | |
@b = BubbleSort.new(a) | |
@b.bubble_up() | |
expect(@b.instance_variable_get(:@stop_flag)).to eq(true) | |
expect(@b.arr).to eq([1, 2, 3]) | |
end | |
it 'repeats the bubbling multiple times' do | |
a = [3, 2, 1] | |
@b = BubbleSort.new(a) | |
@b.bubble_bubble() | |
expect(@b.arr).to eq([1, 2, 3]) | |
end | |
it 'works with about 10 digits' do | |
a = [3, 6, 8, 1, 7, 2, 9, 5, 4] | |
@b = BubbleSort.new(a) | |
@b.bubble_bubble() | |
expect(@b.arr).to eq([1, 2, 3, 4, 5, 6, 7, 8, 9]) | |
end | |
it 'stops executing if array is equal to 1' do | |
a = [7] | |
@b = BubbleSort.new(a) | |
expect(@b).to_not receive(:bubble_up) | |
@b.bubble_bubble() | |
end | |
it 'wont execute a 0 length array' do | |
a = [] | |
@b = BubbleSort.new(a) | |
expect(@b).to_not receive(:bubble_up) | |
@b.bubble_bubble() | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment