1
1
# Author: OMKAR PATHAK
2
+ # Contributors: Mohamed Kiouaz
2
3
# Created On: 31st July 2017
3
4
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)
5
6
6
7
# Bubble Sorting algorithm
7
8
def sort (List ):
@@ -11,11 +12,31 @@ def sort(List):
11
12
List [j ], List [j - 1 ] = List [j - 1 ], List [j ]
12
13
return List
13
14
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
+
14
27
# time complexities
15
28
def 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
+ '''
17
33
18
34
# easily retrieve the source code of the sort function
19
35
def get_code ():
20
36
import inspect
21
37
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