forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Optimized_Bubble_Sort.py
57 lines (45 loc) · 1.69 KB
/
Optimized_Bubble_Sort.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
51
52
53
54
55
56
57
#Optimized Bubble Sort
#Written by XZANATOL
"""
Add a small optimization for Bubble Sort algorithm, so that is stops looping on the given \
list if it is sorted.
"""
def optimized_BS(L):
length = len(L)
for i in range(length):
sorted = 0 #sorted flag
for j in range(length-i-1):
if L[j] > L[j+1]: #Reverse the operator for descending order
L[j], L[j+1] = L[j+1], L[j]
sorted = 1
#If no swaps happened for a complete pass
#Then the array is sorted
if sorted == 0:
break
return L
#Start checkpoint
if __name__ == "__main__":
#Convert to a list so len() function can work on it
L = list(map(int, input("Enter list > ").split()))
print("List after sorting: {} ".format(optimized_BS(L)))
"""
The idea of the sorted flag is that it detects where a swap happenned or not in each pass \
of the for second for loop. If no swaps took place then the list is sorted already, and \
no need for more passes to take place, so it breaks out of the loop.
I/O example:
=============
Input:
Enter list > 65 89 1 4 5 6 87
Output:
List after sorting: [1, 4, 5, 6, 65, 87, 89]
Time Complexity:
=================
Time Complexity here is affected by how the list if first provided. The algorithm takes \
lesser time to order elements when elements are already sorted.
Best case Time Complexity: O(n)
Explain: When the array is already sorted
Worst case Time Complexity: O(n^2)
Explain: Will occur when the array is sorted in the opposite order of the alrogrithm
If the algorithm is configured to sort in ascending order and the provided list is in descending order \
and vice versa.
"""