Bubble Sort | An optimized version of Bubble Sort ; traverse the array from 0 to n - i - 1. Swap if the element found is greater than the next element ; IF no two elements were swapped by inner loop , then break ; Driver code to test above
def bubbleSort ( arr ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT swapped = False NEW_LINE for j in range ( 0 , n - i - 1 ) : NEW_LINE INDENT if arr [ j ] > arr [ j + 1 ] : NEW_LINE INDENT arr [ j ] , arr [ j + 1 ] = arr [ j + 1 ] , arr [ j ] NEW_LINE swapped = True NEW_LINE DEDENT DEDENT if swapped == False : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT arr = [ 64 , 34 , 25 , 12 , 22 , 11 , 90 ] NEW_LINE bubbleSort ( arr ) NEW_LINE print ( " Sorted ▁ array ▁ : " ) NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT print ( " % d " % arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT