-
Notifications
You must be signed in to change notification settings - Fork 0
/
bubble_sort.rb
29 lines (26 loc) · 937 Bytes
/
bubble_sort.rb
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
def bubble_sort(unsorted_array)
last_unsorted_index = unsorted_array.length - 1
while last_unsorted_index.positive?
unsorted_array.each_with_index do |_val, index|
break if index >= last_unsorted_index
if unsorted_array[index] > unsorted_array[index + 1]
unsorted_array[index], unsorted_array[index + 1] = unsorted_array[index + 1], unsorted_array[index]
end
end
last_unsorted_index -= 1
end
unsorted_array
end
def bubble_sort_by(unsorted_array)
last_unsorted_index = unsorted_array.length - 1
while last_unsorted_index.positive?
unsorted_array.each_with_index do |_val, index|
break if index >= last_unsorted_index
if (yield unsorted_array[index], unsorted_array[index + 1]).positive?
unsorted_array[index], unsorted_array[index + 1] = unsorted_array[index + 1], unsorted_array[index]
end
end
last_unsorted_index -= 1
end
unsorted_array
end