-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoptimised_bubblesort.py
More file actions
34 lines (24 loc) · 950 Bytes
/
optimised_bubblesort.py
File metadata and controls
34 lines (24 loc) · 950 Bytes
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
def bubblesort(arr: list) -> list:
"""sorts an array in-place using bubble sort algorithm"""
n = len(arr)
#in the event that there is 0/1 element in an array, there is no necessity to sort
#and we can simply return the array as is. (BASE CASE)
if n <= 1:
return arr
#Optimisation 1: we can skip the final (outer) loop by reducing n to n - 1
for i in range(n - 1):
swapped = False
#Optimisation 2: Skip sorted elements (the ones on the right)
for j in range(n - i - 1):
#traverse the array from 0 to n - 2
#swap if the element found is greater than the next element
if arr[j] > arr[j + 1]:
temp = arr[j]
arr[j] = arr[j + 1]
arr[j + 1] = temp
swapped = True
#OPTIMISATION 3
if not swapped:
return arr
return arr
print(bubblesort([3,2,1]))