Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Python Program for Bubble Sort

  • Difficulty Level : Easy
  • Last Updated : 16 Sep, 2021

Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order. 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.


# Python program for implementation of Bubble Sort
def bubbleSort(arr):
    n = len(arr)
    # Traverse through all array elements
    for i in range(n-1):
    # range(n) also work but outer loop will repeat one time more than needed.
        # Last i elements are already in place
        for j in range(0, n-i-1):
            # traverse the array from 0 to n-i-1
            # Swap if the element found is greater
            # than the next element
            if arr[j] > arr[j + 1] :
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
# Driver code to test above
arr = [64, 34, 25, 12, 22, 11, 90]
print ("Sorted array is:")
for i in range(len(arr)):
    print ("% d" % arr[i]),

Please refer complete article on Bubble Sort for more details! 


def bubblesort(elements):
# Looping from size of array from last index[-1] to index [0]
for n in range(len(elements)-1, 0, -1):
for i in range(n):
if elements[i] > elements[i + 1]:
# swapping data if the element is less than next element in the array
elements[i], elements[i + 1] = elements[i + 1], elements[i]
elements = []
# taking size of array from user
size = int(input("Enter How many number you want to sort:"))
# taking array data from the user
for i in range(size):
value = int(input("Enter the element:"))
print("Array :", elements)
print("Sorted Array is, ")
for i in range(size):
print(elements[i], end =" ")

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!