-
Notifications
You must be signed in to change notification settings - Fork 0
/
bubble.py
50 lines (40 loc) · 1.74 KB
/
bubble.py
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
40
41
42
43
44
45
46
47
48
49
50
from utils import my_length
# wrapper
def bubble_sort(my_list, left=0, right=None):
my_bubble_opt_2(my_list, left, right)
# bubble sort basic with n2 comparisons
def my_bubble_opt_n(my_list, left=0, right=None):
left, right, length = my_length(my_list, left, right)
if length > 0:
# outer loop runs n number of times
for i in range(left, right+1):
# inner loop does pairwise swapping - sinking largest to bottom
for j in range(left, right):
if my_list[j] > my_list[j+1]:
my_list[j], my_list[j+1] = my_list[j+1], my_list[j]
return
# optimized version of my_bubble
def my_bubble_opt_1(my_list, left=0, right=None):
left, right, length = my_length(my_list, left, right)
if length > 0:
for i in range(left, right+1):
# run inner loop few times as we know bottom i-left are already largest
for j in range(left, right - (i-left)):
if my_list[j] > my_list[j+1]:
my_list[j], my_list[j+1] = my_list[j+1], my_list[j]
return
# optimized version my_bubble. Similar to my_bubble_opt_1 and outer loop stops if elements already sorted
def my_bubble_opt_2(my_list, left=0, right=None):
left, right, length = my_length(my_list, left, right)
if length > 0:
swap_active = True
for i in range(left, right+1):
if swap_active is False:
break # stop looping if no more swaps
else:
swap_active = False
for j in range(left, right - (i-left)):
if my_list[j] > my_list[j + 1]:
my_list[j], my_list[j + 1] = my_list[j + 1], my_list[j]
swap_active = True
return