-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbubble_sort.rb
More file actions
36 lines (31 loc) · 888 Bytes
/
bubble_sort.rb
File metadata and controls
36 lines (31 loc) · 888 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
numbers_to_sort = [4,3,78,2,0,2]
def bubble_sort(numbers)
length = numbers.length - 1
unsorted = true
while unsorted
unsorted = false
length.times do |index|
numbers[index], numbers[index+1], unsorted = numbers[index+1], numbers[index], true if numbers[index] > numbers[index+1]
end
length -= 1
end
puts numbers
end
def bubble_sort_by(array_of_things)
length = array_of_things.length - 1
unsorted = true
while unsorted
unsorted = false
length.times do |index|
if yield(array_of_things[index], array_of_things[index+1]) > 0
array_of_things[index], array_of_things[index+1], unsorted = array_of_things[index+1], array_of_things[index], true
end
end
length -= 1
end
puts array_of_things
end
bubble_sort(numbers_to_sort)
bubble_sort_by(["hi","hello","hey"]) do |left,right|
left.length - right.length
end