forked from AaqilSh/DSA-Collection
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBubbleSort.py
More file actions
31 lines (20 loc) · 680 Bytes
/
BubbleSort.py
File metadata and controls
31 lines (20 loc) · 680 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
# Utility function to swap values at two indices in the list
def swap(A, i, j):
temp = A[i]
A[i] = A[j]
A[j] = temp
# Function to perform bubble sort on a list
def bubbleSort(A):
# `len(A)-1` passes
for k in range(len(A) - 1):
# last `k` items are already sorted, so the inner loop can
# avoid looking at the last `k` items
for i in range(len(A) - 1 - k):
if A[i] > A[i + 1]:
swap(A, i, i + 1)
# the algorithm can be terminated if the inner loop didn't do any swap
if __name__ == '__main__':
A = [3, 5, 8, 4, 1, 9, -2]
bubbleSort(A)
# print the sorted list
print(A)