Easy Tutorial
❮ Python Func Complex Python Att Dictionary In ❯

Python Bubble Sort

Python3 Examples

Bubble Sort is also a simple and intuitive sorting algorithm. It repeatedly visits the sequence to be sorted, compares two elements at a time, and swaps them if their order is incorrect. This process is repeated until no more swaps are needed, indicating that the sequence is sorted. The name of the algorithm comes from the fact that smaller elements "bubble" to the top of the list through exchanges.

Example

def bubbleSort(arr):
    n = len(arr)

    # Traverse through all array elements
    for i in range(n):

        # Last i elements are already in place
        for j in range(0, n-i-1):

            if arr[j] > arr[j+1] :
                arr[j], arr[j+1] = arr[j+1], arr[j]

arr = [64, 34, 25, 12, 22, 11, 90]

bubbleSort(arr)

print ("Sorted array:")
for i in range(len(arr)):
    print ("%d" %arr[i]),

Executing the above code produces the following output:

Sorted array:
11
12
22
25
34
64
90

Python3 Examples

❮ Python Func Complex Python Att Dictionary In ❯