Python program for bubble sort [3 methods]

In this Python article, I will explain how to write a Python program for bubble sort using different methods with some illustrative examples. Here, I will also explain what bubble sorting is, how bubble sort works in Python, and different ways to implement Python program for bubble sort.

What is Bubble sorting in Python list?

Bubble sort is a simple sorting algorithm that repeatedly steps through the Python list of elements to be sorted, compares adjacent elements, and swaps them if they are in the wrong order. This process is repeated until the entire Python list is sorted.

Working on bubble sort

Let’s take a simple example and understand what Bubble sort means. So, here we will take a Python list that contains some integer value:

``Initial_List  = [25, 17, 7, 14, 6, 3]``

Explanation: To bubble sort the Python list [25, 17, 7, 14, 6, 3], we would repeatedly compare adjacent elements and swap them if they are in the wrong order until the entire list is sorted. Here’s how the bubble sort algorithm would work step by step for our Python list:

Pass 1:

After the first pass, the largest element (25) has been bubble-sorted to the end of the Python list.

Pass 2:

After the second pass, the second largest element (17) has moved to the second-to-last position in the Python list.

Pass 3:

After the third pass, the third largest element (14) has moved to the third-to-last position in the Python list.

Pass 4:

After the fourth pass, the fourth largest element (7) has moved to the fourth-to-last position in the list of Python.

Pass 5:

After the fifth pass, the fifth largest element (6) has moved to the fifth-to-last position in the list of Python.

Pass 6:

The list in Python is now fully sorted, and no more swaps are needed.

``Final Sorted List: [3, 6, 7, 14, 17, 25]``

The Python list is now sorted in ascending order using the bubble sort algorithm.

I have also created an image to make you better understand this whole process:

As we can see no swap is happening in the sixth pass, that’s why I have not mentioned it in the image.

Methods and ways used in Python program for bubble sort

There are different methods and ways present in Python that can be used to write a Python program for bubble sort:

Methods:

1. For loop
2. while loop
3. List comprehension

Ways:

1. using function
2. without using function
3. taking user input

Method 1: Bubble sort Python using for loop

A for loop is used in the Bubble Sort algorithm to repeatedly iterate through the list, comparing adjacent elements and swapping them if necessary.

Let’s take an example and understand how the for loop can be used within a Python Python program for bubble sort:

Example: In this scenario, we will be using a nested for loop for bubble sort:

Code:

``````def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
# Example usage:
unsorted_list = [5, 2, 9, 1, 5]
sorted_list = bubble_sort(unsorted_list)
print("Sorted list:", sorted_list)``````

Output: Within the inner for loop in Python, the if conditional statement compares the current element with the next element. If the current element is greater than the next element, the elements are swapped using the assignment operator(=) in Python.

The combination of the outer and inner for loops in Bubble Sort allows the algorithm to gradually sort the Python list by comparing and swapping adjacent elements until the entire list in Python is sorted in ascending order.

``Sorted list: [1, 2, 5, 5, 9]``

This way we can simply use the for loop or we can say nested for loop to write a Python program for bubble sort.

Method 2: Bubble sort using while loop in Python

Using a while loop for Bubble Sort in Python involves iterating through the Python list until no more swaps are required, indicating that the Python list is sorted.

Here’s an explanation of how Bubble Sort can be implemented in Python with a while loop using an example:

``````my_list = [64, 34, 25, 12, 22, 11, 90]

n = len(my_list)
swapped = True  # Initialize swapped as True to enter the loop

while swapped:
swapped = False  # Reset swapped for this pass
for i in range(1, n):
if my_list[i - 1] > my_list[i]:
# Swap the elements
my_list[i - 1], my_list[i] = my_list[i], my_list[i - 1]
swapped = True  # Set swapped to True if a swap occurs

# Print the sorted list
print("Sorted list is:", my_list)``````

Output: The while loop continues until no more swaps are needed during a pass through the list, indicating that the Python list is sorted. Inside the while loop, an inner for loop iterates through the list in Python, comparing adjacent elements and swapping them when necessary.

If a swap is made during a pass, the swapped flag is set to True, indicating that another pass may be needed. After the while loop terminates, the list in Python will be sorted in ascending order.

``Sorted list is: [11, 12, 22, 25, 34, 64, 90]``

This way we can simply use the while loop with a for loop and swapped flag we can write a Python program for bubble sort.

Method 3: Bubble sort in Python using list comprehension

List comprehension is a concise and readable way to create lists in Python. It allows us to generate a new list in Python by applying an expression to each item in an existing iterable while optionally applying a condition to filter items.

List comprehension is typically not used for sorting algorithms like Bubble Sort because Bubble Sort involves in-place swapping of elements, which isn’t well-suited to the declarative nature of list comprehensions. However, we can use list comprehensions for other operations related to sorting, such as creating a sorted copy of a list in Python or filtering elements based on certain conditions.

Example: let’s use list comprehensions to create a new sorted list in Python from an existing Python list, without modifying the original list. We’ll essentially be implementing a simplified version of the Python program for Bubble Sort using list comprehensions:

``````original_list = [64, 34, 25, 12, 22, 11, 90]
# List comprehension to create a sorted copy
sorted_list = [x for x in sorted(original_list)]
# Print the sorted list
print("Original list:", original_list)
print("Sorted list:", sorted_list)``````

Output: In this code, we start with an original_list Python list containing unsorted elements. We use the sorted() function in Python, which returns a new sorted list without modifying the original Python list. Then, we use a list comprehension to create the sorted_list Python list, which contains the sorted elements. Finally, we print both the original and sorted lists in Python.

``````Original list: [64, 34, 25, 12, 22, 11, 90]
Sorted list: [11, 12, 22, 25, 34, 64, 90]``````

This code doesn’t implement the Bubble Sort Python program using list comprehensions but uses list comprehensions in conjunction with the sorted() function to create a sorted copy of the original list in Python.

Way 1: Bubble sort in Python with using function

Here’s an implementation of the Bubble Sort algorithm using a Python function:

Code:

``````def bubble_sort(input_list):
n = len(input_list)
for _ in range(n):
swapped = False
for i in range(1, n):
if input_list[i - 1] > input_list[i]:
# Swap the elements
input_list[i - 1], input_list[i] = input_list[i], input_list[i - 1]
swapped = True
# If no swaps were made in this pass, the list is sorted
if not swapped:
break
return input_list

input_list = [64, 16, 5, 41, 29, 20]
sorted_list = bubble_sort(input_list)
# Print the sorted array
print("Sorted list is:", sorted_list)``````

Output: we have just applied the for loop method inside the Python function to write a Python program for bubble sort. And this is how we create a bubble sort Python program with a function.

``Sorted list is: [5, 16, 20, 29, 41, 64]``

Way 2: Bubble sort in Python without using function

We can implement the Bubble Sort algorithm in Python without using a separate function. Here’s a simple example of how to do it:

Code:

``````My_list = [64, 34, 25, 12, 22, 11, 90]
n = len(My_list)
for i in range(n):
# Flag to optimize the algorithm
swapped = False
for j in range(0, n-i-1):
if My_list[j] > My_list[j+1]:
# Swap the elements
My_list[j], My_list[j+1] = My_list[j+1], My_list[j]
swapped = True
# If no two elements were swapped in the inner loop, the list is already sorted
if not swapped:
break

print("Sorted list is:", My_list)``````

Output: This is as same as for loop but it also contains a swapped flag to write a Python program for Bubble sort without a function

``Sorted list is: [11, 12, 22, 25, 34, 64, 90]``

Way 3: Bubble sort in Python with user input

We can modify the Python program to take user input for the list that needs to be Bubble sorted. Here’s an example of how to do it:

Code:

``````# Taking user input for the list of numbers
input_str = input("Enter a list of numbers separated by spaces: ")
input_list = [int(x) for x in input_str.split()]

n = len(input_list)
for i in range(n):
swapped = False
for j in range(0, n-i-1):
if input_list[j] > input_list[j+1]:
# Swap the elements
input_list[j], input_list[j+1] = input_list[j+1], input_list[j]
swapped = True
if not swapped:
break

print("Sorted list is:", input_list)``````

Output: In this case also, we have used the for loop method to bubble sort in Python. But. instead of providing the list that is going to be sorted, we provide a code that will take user input and create a list with the help of the list comprehension method in Python.

``````Enter a list of numbers separated by spaces: 16 64 5 29 20 41 111 102
Sorted list is: [5, 16, 20, 29, 41, 64, 102, 111]``````

Conclusion

Understanding what bubble sorting is, how we can write a Python program for bubble sort using three different methods for loop, while loop, and list comprehension. And, what are the different ways we can implement the bubble sort in Python,

You may also like to read in Python: