-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbubble_sorting.py
More file actions
36 lines (29 loc) · 840 Bytes
/
Copy pathbubble_sorting.py
File metadata and controls
36 lines (29 loc) · 840 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
35
36
"""
Bubble sort sorts a list by repeatedly
swapping adjacent out-of-order values.
The process continues until the list
becomes sorted.
Let n denote the size of the list.
Time complexity: O(n^2)
Space complexity: O(1)
"""
def bubble_sort(array):
isSorted = False
passes = 0
length = len(array)
while not isSorted:
isSorted = True
# Perform a pass through the array
# excluding already sorted positions
for i in range(length-1-passes):
if(array[i] > array[i+1]):
swap(i, i+1, array)
# Array is not sorted yet
isSorted = False
passes += 1
return array
def swap(i, j, array):
# Swap values at indices i and j
array[i], array[j] = array[j], array[i]
arr = [1, 9, 3, 2]
print(bubble_sort(arr)) # [1, 2, 3, 9]