Bubble sort program in Python

Written by

Himani Kohli

How Bubble sort works ?

Bubble sort is a simple sorting algorithm that compares the adjacent numbers in an array and swaps them if they are in the wrong order.

It is also referred to as a sinking sort.

In this program, we will learn to implement bubble sort in an array in order to sort the array in increasing order. Although the algorithm is simple but it is slow and impractical for some problems when it is compared to insertion sort.


  1. An array[arr] is initialized.
  2. Length of the array is stored in a variable n.
  3. For each value in array, a loop is generated.
  4. For each value of the iteration from (3) a loop is generated excluding these many items because they are sorted towards the end.
  5. Swap if a bigger number is encountered using a temporary variable “temp”.
  6. Loop ends 4.
  7. Loop ends 3.
  8. Print the sorted array, which is in place of the original array now.
  9. Exit 

Code for bubble sort python:



for i in range(n):

    for j in range(0,n-i-1):

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




print("Sorted Array : ", arr )



Sorted Array : [1, 2, 3, 5, 6, 9]


Bubble sort program in Python