11# Author: OMKAR PATHAK
2+ # Contributors: Mohamed Kiouaz
23# Created On: 31st July 2017
34
4- # Best O(n^2 ); Average O(n^2 ); Worst O(n^2)
5+ # Best O(n); Average O(n*(n-1)/4 ); Worst O(n^2)
56
67# Bubble Sorting algorithm
78def sort (List ):
@@ -11,11 +12,31 @@ def sort(List):
1112 List [j ], List [j - 1 ] = List [j - 1 ], List [j ]
1213 return List
1314
15+ # Improved Bubble Sorting algorithm
16+ def improved_sort (List ):
17+ for i in range (len (List )):
18+ stop = True
19+ for j in range (len (List ) - 1 , i , - 1 ):
20+ if List [j ] < List [j - 1 ]:
21+ stop = False
22+ List [j ], List [j - 1 ] = List [j - 1 ], List [j ]
23+ if (stop == True ):
24+ return List
25+ return List
26+
1427# time complexities
1528def time_complexities ():
16- return '''Best Case: O(n ^ 2), Average Case: O(n ^ 2), 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+ '''
1733
1834# easily retrieve the source code of the sort function
1935def get_code ():
2036 import inspect
2137 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