bubble sort in python

In this tutorial, you will learn how bubble sort work and how to perform bubble sort with example.

The bubble sort makes multiple passes through a list. It compares adjacent items and exchanges those that are out of order. Each pass through the list places the next largest value in its proper place. In essence, each item (bubbles) up to the location where it belongs.

Example :

    
# python program to sort array using bubble sort
def bubbleSort(arr):
    for passnum in range(len(arr)-1,0,-1):
        for i in range(passnum):
            if arr[i]>arr[i+1]:
                temp = arr[i]
                arr[i] = arr[i+1]
                arr[i+1] = temp
    return arr

arr = [10,4,3,9,8,2,5,6]

print("Before Sorted :: ",arr)
print("After Sorted :: ",bubbleSort(arr))
       

Output :

    
Before Sorted ::  [10, 4, 3, 9, 8, 2, 5, 6]
After Sorted ::  [2, 3, 4, 5, 6, 8, 9, 10]
    

A bubble sort is often considered the most inefficient sorting method since it must exchange items before the final location is known. These wasted exchange operations are very costly. However, because the bubble sort makes passes through the entire unsorted portion of the list, it has the capability to do something most sorting algorithms cannot.


Share your thoughts

Ask anything about this examples