Skip to content

Instantly share code, notes, and snippets.

@JoshCheek
Created September 15, 2015 15:11
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 JoshCheek/d57281e34adf6fdb10d8 to your computer and use it in GitHub Desktop.
Save JoshCheek/d57281e34adf6fdb10d8 to your computer and use it in GitHub Desktop.
Blowing Bubbles 2 midpoint

Blowing Bubbles 2 takes this bubble sort:

a = ["e", "a", "c", "b", "d"]
b = 0

while b < a.length
  c = 0
  d = 1

  while d < a.length
    e = a[c]
    f = a[d]
    if f < e
      a[c]  = f
      a[d] = e
    end
    c += 1
    d += 1
  end

  b += 1
end

a

Through a series of transformations until it becomes this Bubble Sort:

class SortAlgorithms
  class BubbleSort
    attr_reader :array

    def initialize(array)
      @array = array
    end

    def sort
      array.each { bubble_across }
      array
    end
    
    def bubble_across
      (array.length-1).times { |index| bubble_once index }
    end

    def bubble_once(index)
      swap(index) if swap?(index)
    end

    def swap?(index)
      array[index+1] < array[index]
    end
    
    def swap(index)
      array[index], array[index+1] = array[index+1], array[index]
    end
  end
end

SortAlgorithms::BubbleSort.new(["e", "a", "c", "b", "d"]).sort
# => ["a", "b", "c", "d", "e"]

And then takes it back to the start. Here is a video of me going through it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment