BeginnerCoder
intermediate#algorithms#bubble sort#python

Implementing Bubble Sort

This article was AI-drafted and has not been reviewed yet. Spotted a mistake? Tell us.

Learn how to implement the bubble sort algorithm to sort an array of numbers.

Implementing Bubble Sort

Introduction

This tutorial will guide you through implementing the bubble sort algorithm to sort an array of numbers.

Step 1: Define the Problem

We are given an array of numbers and we need to sort it in ascending order.

Step 2: Initialize the Outer Loop

We will initialize an outer loop that iterates through the array.

Step 3: Initialize the Inner Loop

We will initialize an inner loop that iterates through the unsorted portion of the array.

Step 4: Compare Adjacent Elements

We will compare adjacent elements and swap them if they are in the wrong order.

Step 5: Repeat Steps 3 and 4 Until the Array is Sorted

We will repeat steps 3 and 4 until the array is sorted.

Example Code

def bubble_sort(array):
    n = len(array)
    for i in range(n):
        for j in range(0, n-i-1):
            if array[j] > array[j+1] :
                array[j], array[j+1] = array[j+1], array[j]
    return array
print(bubble_sort([64, 34, 25, 12, 22, 11, 90]))  # Output: [11, 12, 22, 25, 34, 64, 90]

Conclusion

In this tutorial, we learned how to implement the bubble sort algorithm to sort an array of numbers.

Keep going with algorithms

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.