December 22, 2024

How to Bubble Sort in Python

Bubble Sort is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items, and swapping them if they are in the wrong order. This process is repeated until no swaps are needed, which indicates that the list is sorted.

Here is a step-by-step guide on how to implement the Bubble Sort algorithm in Python:

  1. Start by defining a function that takes a list of elements as a parameter.
  2. Create a variable ‘n’ to store the length of the list.
  3. Use a nested loop to iterate through the list. The outer loop will run ‘n’ times, and the inner loop will run ‘n-i-1’ times, where ‘i’ is the current iteration of the outer loop.
  4. Within the inner loop, compare adjacent elements. If the elements are in the wrong order, swap them.
  5. Continue this process until the list is fully sorted.
  6. Finally, return the sorted list.

Now, let’s put this into 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
my_list = [64, 34, 25, 12, 22, 11, 90]
print(bubble_sort(my_list))

By following this guide and code snippet, you can successfully implement the Bubble Sort algorithm in Python to efficiently sort a list of elements. While Bubble Sort is not the most efficient sorting algorithm, it is a great way to learn about sorting algorithms and how they work.

Leave a Reply

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