Table of Contents

Bubble Sort in Python

Example Description
Dive into the world of bubble sort algorithm using Python. Explore a step-by-step guide to implement bubble sort with practical examples. Learn how to efficiently sort a list of elements in ascending order using this simple yet effective sorting technique.

Introduction:

Bubble sort is a fundamental sorting algorithm that can be implemented using Python. This tutorial provides a comprehensive guide to implementing the bubble sort algorithm. Through practical examples and explanations, you’ll understand the logic behind bubble sort and how it efficiently sorts a list of elements in ascending order.

Code:

def bubble_Sort(list1):  # Number of passes
    n = len(list1)
    for i in range(n):
        for j in range(0, n-i-1): # size -i-1 because last i elements are already sorted 
            if list1[j] > list1[j+1]: # Swap element at jth position with (j+1)th position
                list1[j], list1[j+1] = list1[j+1], list1[j]

numList = [8, 7, 13, 1, -9, 4]
bubble_Sort(numList)
print("The sorted list is:")
for i in range(len(numList)):
    print(numList[i], end=" ")

Logic:

  1. Define the bubble_sort function that takes a list list1 as input.
  2. Get the length of the list n.
  3. Use nested loops to perform the bubble sort:
  4. The outer loop runs for n passes (one pass for each element).
  5. The inner loop compares adjacent elements and swaps them if necessary, effectively moving the largest element to the end of the list.
  6. The sorted list is printed after the sorting process is complete.

Output:

>The sorted list is:

>>-9 1 4 7 8 13