Python Program for Bubble Sort

In this tutorial, we will discuss a Python program for the bubble sort algorithm to sort an array of numbers in ascending order.

Before going to the program first, let us understand what is Bubble Sort.

Bubble Sort:

  • Bubble sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order.

Related: Python Program to Find the LCM of Two Numbers

Program code for Bubble Sort in Python

# Bubble Sort in Python
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]
 
arr = [64, 34, 25, 12, 22, 11, 90]
bubble_sort(arr)
print("Sorted array:", arr)

Explanation

  1. Function Definition: The bubble_sort function takes an array arr as input and sorts it in ascending order using the bubble sort algorithm.
  2. Main Program: The program defines an unsorted array and sorts it using the bubble_sort function. It then prints the sorted array.

Output

Python Program for Bubble Sort

  • When you run the above program, it will sort the array using bubble sort and print the sorted result.

Conclusion

  • In this tutorial, we learned how to implement the bubble sort algorithm in Python.
  • Understanding this concept is essential for solving various sorting problems and enhancing your programming skills.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *