Class: Sorting::BubbleSort

Inherits:
Object
  • Object
show all
Extended by:
Helper
Defined in:
lib/sorting/bubble_sort.rb

Constant Summary collapse

TEST_DATA_SIZE =
1000

Class Method Summary collapse

Methods included from Helper

sort

Class Method Details

.sort!(data) ⇒ Object

Bubble Sort Comparison sort Exchanging Stable Time complexity: Ω(n), Ө(n2), O(n2) Space complexity: O(n) total, O(1) auxiliary Tiny code size



14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/sorting/bubble_sort.rb', line 14

def self.sort!(data)
  max_i = data.size - 1
  (0...max_i).each do |i|
    swapped = false
    (0...(max_i-i)).each do |j|
      if data[j] > data[j+1]
        data[j], data[j+1] = data[j+1], data[j] 
        swapped = true
      end
    end
    break if !swapped
  end
  nil
end