BUBBLE SORT

COMPARE · SWAP · REPEAT


prostudypk.com
Sorting an Array a[0]a[1]a[2]a[3]a[4] 51428 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 numbersIf the first is bigger, swap them After each pass the largest is fixed at the end
3. Remember n elements → (n − 1) passesThe largest value bubbles up to the end
MATRIC COMPUTER · ALGORITHMS · PUNJAB BOARDS
‹ Labs Next ›