BUBBLE SORT
COMPARE · SWAP · REPEAT
prostudypk.com
Sorting an Array
a[0]
a[1]
a[2]
a[3]
a[4]
5
1
4
2
8
Pass
of 4
comparisons
swaps
1. Algorithm (Code)
for i in range(n-1):
for j in range(n-1-i):
if a[j] > a[j+1]:
swap(a[j], a[j+1])
2. Steps
Compare two neighbouring numbers
If the first is bigger,
swap
them
After each pass the largest is
fixed at the end
3. Remember
n elements → (n − 1) passes
The largest value bubbles up to the end
MATRIC COMPUTER · ALGORITHMS · PUNJAB BOARDS
‹ Labs
↺
❚❚
1×
Next ›