-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbubble_sort.rb
More file actions
39 lines (37 loc) · 835 Bytes
/
Copy pathbubble_sort.rb
File metadata and controls
39 lines (37 loc) · 835 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
# Time Complexity: O(n^2)
# Bubble sort is slowest sorting algorithm
# Arranging elements based on increasing order swapping.
# Bubble Sort Implementation (works by repeatedly swapping the adjacent elements if they are in wrong order.)
# a = [9,100,2,3,4,5] n = 6
def bubble_sort_descending(a)
n = a.length
for i in 0...n-1 do # N-1 Passes
flag = 0
for j in 0...n-i-1 do
if a[j] > a[j+1]
tmp = a[j]
a[j] = a[j+1]
a[j+1] = tmp
flag = 1
end
end
break if flag == 0
end
return a
end
def bubble_sort_ascending(a)
n = a.length
for i in 0...n-1 do # N-1 Passes
flag = 0
for j in 0...n-i-1 do
if a[j] < a[j+1]
tmp = a[j]
a[j] = a[j+1]
a[j+1] = tmp
flag = 1
end
end
break if flag == 0
end
return a
end