Bubble Sort in Python

In this class, we write a program for bubble sort in python.

For Complete YouTube Video: Click Here

Bubble Sort

Q1) Write a program to take a list of integers and sort them in ascending order using bubble sort.

Example:

Input: [8,2,5,1,7,4,9,6]

Output: [1,2,4,5,6,7,8,9]

Logic

The reader should have an idea about bubble sort. Here we concentrate on implementation in python.

If you do not have any knowledge of bubble sort. Please go to our data structure course.

To implement bubble sort, one should be good in the nested loops concept. Click here.

Example:

input=[8,2,5,1,7,4,9,6]

Total eight elements present from index position zero to index position seven.

First iteration:

Start from index position zero.

Compare the element present in index position zero with the element in index position one.

If an element in index position zero is greater. Swap the elements in positions zero and one.

Next, compare the element present in index position one with the element in index position two.

Suppose an element in index position one is greater. Swap the elements in positions one and two.

Repeat this to the last element is compared with the last before element.

After first iteration the elements in the list look like [2,5,1,7,4,8,6,9].

We observe from the first iteration. The largest element is moved to the last location.

Second iteration

In the second iteration, leave the last element position and repeat the above process done in the first iteration.

In the second iteration, we move the second largest element to the last before position.

Each iteration is moving the largest element to the right side.

To implement this, we need a nested loop.

To do one iteration, we need a loop.

Repeat the same logic for n-1 times. Here n is the number of elements.

In each iteration, reduce the size of the list to be considered. Because elements are moving right need not be considered again.

The program is given below. Understand the logic for better coding practice.

Program

elements=[]
n=int(input("enter no of elements"))
for i in range(n):
    ele=int(input("enter element"))
    elements.append(ele)
for i in range(n-2,-1,-1):
    for j in range(i+1):
        if(elements[j]>elements[j+1]):
            temp=elements[j]
            elements[j]=elements[j+1]
            elements[j+1]=temp
print(elements)