- Notifications
You must be signed in to change notification settings - Fork 152
/
Copy pathbubble_sort.py
40 lines (28 loc) · 1021 Bytes
/
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
# A simple implementation of bubble sort
defbubbleSort(arr):
# travese the whole array
foriinrange(len(arr)):
# last i elements are already in place
forjinrange(0, len(arr)-i-1):
ifarr[j] >arr[j+1]:
arr[j], arr[j+1] =arr[j+1], arr[j]
returnarr
# Approach 2: This algorithm will run for O(n^2) even if the array is
# already sorted. For avoiding this, we can check if elements are swapped
# in each pass. We will break the loop in case they are not
# Time Complexity: O(n^2) - Average or Worst Case; O(n) - Best case [Array is already sorted]
defbubbleSortOptimized(arr):
foriinrange(len(arr)):
swapped=False
forjinrange(0, len(arr)-i-1):
ifarr[j] >arr[j+1]:
arr[j], arr[j+1] =arr[j+1], arr[j]
swapped=True
# if no elements are swapped, break the loop
ifswapped==False:
break
returnarr
if__name__="__main__":
arr= [2, 6, 1, 5, 3, 4]
res=bubbleSort(arr)
print(res)