-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbubble_sort.rb
More file actions
38 lines (30 loc) · 816 Bytes
/
bubble_sort.rb
File metadata and controls
38 lines (30 loc) · 816 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
def bubble_sort(array)
loop do
array.each_with_index.reduce() do |prev_num_and_index, next_num_and_index|
prev_num = prev_num_and_index[0]
next_num = next_num_and_index[0]
prev_num_position = prev_num_and_index[1]
next_num_position = next_num_and_index[1]
if prev_num > next_num
array.insert(next_num_position, array.delete_at(prev_num_position))
end
[array[next_num_position], next_num_position]
end
break if sorted?(array)
end
array
end
def sorted?(array)
sorted = true
arr = array.rotate(0) # Copy of the array
array.each do |prev_num|
unless arr.all? { |next_num| prev_num <= next_num }
sorted = false
break
end
arr.shift
end
sorted
end
p bubble_sort([4,3,78,2,0,2])
p bubble_sort([-1,4,3,78,2,0,2,79])