Skip to content

Commit 6850ae1

Browse files
authored
Added improved bubble sort
Added improved_sort() functions and updated time complexities for improved_sort() method. For retrieving code of improved_sort(), simply fire `bubble_sort.get_improved_code()`
1 parent 8caa96e commit 6850ae1

File tree

1 file changed

+17
-1
lines changed

1 file changed

+17
-1
lines changed

pygorithm/sorting/bubble_sort.py

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,14 @@
66

77
# Bubble Sorting algorithm
88
def sort(List):
9+
for i in range(len(List)):
10+
for j in range(len(List) - 1, i, -1):
11+
if List[j] < List[j - 1]:
12+
List[j], List[j - 1] = List[j - 1], List[j]
13+
return List
14+
15+
# Improved Bubble Sorting algorithm
16+
def improved_sort(List):
917
for i in range(len(List)):
1018
stop = True
1119
for j in range(len(List) - 1, i, -1):
@@ -18,9 +26,17 @@ def sort(List):
1826

1927
# time complexities
2028
def time_complexities():
21-
return '''Best case O(n); Average case O(n * (n - 1) / 4); Worst case O(n ^ 2)'''
29+
return '''Best Case: O(n ^ 2), Average Case: O(n ^ 2), Worst Case: O(n ^ 2)
30+
For Improved Bubble Sort:
31+
Best Case: O(n); Average Case: O(n * (n - 1) / 4); Worst Case: O(n ^ 2)
32+
'''
2233

2334
# easily retrieve the source code of the sort function
2435
def get_code():
2536
import inspect
2637
return inspect.getsource(sort)
38+
39+
# easily retrieve the source code of the sort function
40+
def get_improved_code():
41+
import inspect
42+
return inspect.getsource(improved_sort)

0 commit comments

Comments
 (0)