
Outer loop: conditional while loop
Inner loop: count-controlled for loop
def BubbleSort(array):
num=len(array)
i=0
Swap=True
while Swap==True:
Swap=False
for i in range(num-1):
if array[i]> array[i+1]:
Temp=array[i]
array[i]=array[i+1]
array[i+1]=Temp
Swap=True
num-=1
array[i],array[i+1]=array[i],array[i+1]
1. range(num-1)
- Adjusted Loop Range:
- to avoid accessing
array[i + 1]wheniis the last valid index.
- Efficient Range Reduction:
- After each pass, the largest unsorted element is moved to its correct position, so reducing
numensures that portion is not rechecked unnecessarily
2. num-=1 after for loop ends
- to reduce 1 pass after 1 pass have been successfully done
3. pass VS swap
1st passes have many swaps
- the outer while loop control number of passes
- the inner for loop control swaps




def bubbleSort(arr):
for passes in range(len(arr) - 1):
for swaps in range(len(arr) - 1 - passes):
if arr[swaps] > arr[swaps + 1]:
arr[swaps + 1], arr[swaps] = arr[swaps], arr[swaps + 1]
# arr[swaps] = arr[swaps + 1] (alternative for above line)
# arr[swaps + 1] = temp (alternative for above line)
return arr
def bubbleSortReverse(arr):
for passes in range(len(arr) - 1):
for swaps in range(len(arr) - 1 - passes):
if arr[swaps] < arr[swaps + 1]:
arr[swaps + 1], arr[swaps] = arr[swaps], arr[swaps + 1]
# temp = arr[swaps] (alternative for above line)
# arr[swaps] = arr[swaps + 1] (alternative for above line)
# arr[swaps + 1] = temp (alternative for above line)
return arr
Recursive Bubble
def RecursiveBubbleSort(IntegerArray,int(First),int(Last),int(ToFind)):