forked from kelvins/algorithms-and-data-structures
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbubble_sort.rb
More file actions
39 lines (31 loc) · 661 Bytes
/
bubble_sort.rb
File metadata and controls
39 lines (31 loc) · 661 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# frozen_string_literal: true
# Sort an array using the BubbleSort algorithm
class Bubblesort
attr_reader :array_sorted
def initialize
@array_sorted = []
end
def init(array)
bubble_sort(array)
end
private
def bubble_sort(array)
return nil if array.empty?
n = array.length - 1
loop do
swapped = false
n.times do |i|
if array[i] > array[i + 1]
array[i], array[i + 1] = array[i + 1], array[i]
swapped = true
end
end
break unless swapped
end
@array_sorted = array
end
end
# test
b_s = Bubblesort.new
b_s.init([1, 4, 10, 2, 3, 32, 0])
p b_s.array_sorted