Python Program for Bubble Sort

Bubble Sort in Python: In this tutorial, we will learn about the bubble sort, its implementation, how to implement bubble sort in an array or list in Python. By Soumya Sinha Last updated : April 21, 2023

What is Bubble Sort?

Bubble sort is a sorting algorithm that is used to sort an array or list. Bubble Sort is one of the easiest sorting algorithms among all other sorting algorithms. In this algorithm, one needs to repeatedly compare the elements one by one and swap the adjacent elements to bring them in the correct sorted order. If there are n number of elements within the array then each element will undergo n-1 comparisons. This way after comparing one element with other elements within the array, an element is placed at its place in the sorted list similar to a bubble rising up and moving. That is why this algorithm is known as Bubble Sort. The number of comparisons in this algorithm is more thus its complexity is more.

Procedure for Bubble Sort

The procedure of bubble sort is as follows:

BubbleSort (arr):
   n =len(arr)
   For i=0 to n-1:
       For j=1 to n-i-1:
           If arr[i] > arr[j]:
               Swap(arr[i],arr[j])

Bubble Sort Example

First Pass:

7 5 0 2 4 ) –> ( 5 7 0 2 4 ), The algorithm compares the first two elements, and swaps      since 7 > 5.
( 5 7 0 2 4 ) –>  ( 5 0 7 2 4 ), Swap since 7 > 0
( 5 0 7 2 4 ) –>  ( 5 0 2 7 4 ), Swap since 7 > 2
( 5 0 2 7 4 ) –> ( 5 0 2 4 7 ), Swap since 7 > 4

Second Pass:

5 0 2 4 7 ) –> ( 0 5 2 4 7 ), Swap since 5 > 0
( 0 5 2 4 7 ) –> ( 0 2 5 4 7 ), Swap since 5 > 2
( 0 2 4 5 7 ) –> ( 0 2 4 5 7 ), No swap as the elements are already sorted
( 0 2 4 5 7 ) –>  ( 0 2 4 5 7 ), No swap as the elements are already sorted
We can see that the array is already sorted, but our algorithm does not know this. The algorithm needs one complete pass without any swap to know if the array is sorted or not.

Third Pass:

0 2 4 5 7 ) –> ( 0 2 4 5 7 )
( 0 2 4 5 7 ) –> ( 0 2 4 5 7 )
( 0 2 4 5 7 ) –> ( 0 2 4 5 7 )
( 0 2 4 5 7 ) –> ( 0 2 4 5 7 )

Time Complexity: O(n^2)

Python program to implement bubble sort

import sys

def bubble_sort(arr):
    # This function will sort the array in non-decreasing order. 
    n = len(arr)
    #Traverse through all the array elements
    for i in range(n):
        # The inner loop will run for n-i-1 times as the
        # last i elements are already in place.
        for j in range(0, n-i-1):
        # Swap if the present element is greater than the
        # next element.
            if arr[j] > arr[j+1]:
                temp = arr[j]
                arr[j] = arr[j+1]
                arr[j+1] = temp 
    return arr

# main code
if __name__=='__main__':

    arr = [2, 1, 9, 3, 7, 5, 6, 4, 8, 0]
    print("Sorted array: ")
    print(bubble_sort(arr))

Output

Sorted array: 
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Bubble Sort Optimized Implementation

The above function always runs O(n^2) time even though the array is sorted. We can prevent this by stopping the algorithm if inner loop didn’t cause any swap.

Python program to implement bubble sort (optimized approach)

import sys

def bubble_sort(arr):
    # This function will sort the array in non-decreasing order. 
    n = len(arr)
    #Traverse through all the array elements
    for i in range(n):
        swap = False
        # The inner loop will run for n-i-1 times as the
        # last i elements are already in place.
        for j in range(0, n-i-1):
        # Swap if the present element is greater than the
        # next element.
            if arr[j] > arr[j+1]:
                temp = arr[j]
                arr[j] = arr[j+1]
                arr[j+1] = temp 
                swap = True
        # If no two elements were swapped 
        # by inner loop, then break 
        if swap == False:
            break
    return arr

# main code
if __name__=='__main__':

    arr = [2, 1, 9, 3, 7, 5, 6, 4, 8, 0]
    print("Sorted array: ")
    print(bubble_sort(arr))

Time Complexity

  • Best Case: O(n)
  • Worst Case: O(n^2)

Python Data Structure Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.