Loading...

Section

Sorting a Small List: Bubble Sort Introduction

Part of The Prince Academy's AI & DX engineering stack.

Follow The Prince Academy Inc.

We've explored the fundamental building blocks of algorithms – the steps and logic. Now, let's put that knowledge into practice with our first complete algorithm example. One of the most intuitive sorting algorithms is called Bubble Sort. Imagine you have a list of numbers that are all mixed up, and you want to arrange them in ascending order. Bubble Sort works by repeatedly stepping through the list, comparing adjacent elements and swapping them if they are in the wrong order. This process is repeated until the list is sorted.

Think of it like bubbles rising to the surface. In each pass, the largest unsorted element 'bubbles up' to its correct position at the end of the unsorted portion of the list. We continue these passes until no more swaps are needed, indicating that the list is fully sorted.

graph TD; A[Start] --> B{Is list sorted?}; B -- No --> C[Compare adjacent elements]; C --> D{Swap if out of order?}; D -- Yes --> E[Perform Swap]; E --> C; D -- No --> F[Move to next pair]; F --> B; B -- Yes --> G[End];

Let's visualize how Bubble Sort works with a small example list: [5, 1, 4, 2, 8].

Pass 1:

  • Compare 5 and 1. They are out of order, so swap: [1, 5, 4, 2, 8]
  • Compare 5 and 4. They are out of order, so swap: [1, 4, 5, 2, 8]
  • Compare 5 and 2. They are out of order, so swap: [1, 4, 2, 5, 8]
  • Compare 5 and 8. They are in order. No swap.

After Pass 1, the largest element (8) is in its correct final position.

Pass 2: (We only need to consider the unsorted portion [1, 4, 2, 5])

  • Compare 1 and 4. They are in order. No swap.
  • Compare 4 and 2. They are out of order, so swap: [1, 2, 4, 5, 8]
  • Compare 4 and 5. They are in order. No swap.

After Pass 2, the second largest element (5) is in its correct final position.

Pass 3: (We only need to consider the unsorted portion [1, 2, 4])

  • Compare 1 and 2. They are in order. No swap.
  • Compare 2 and 4. They are in order. No swap.

No swaps occurred in this pass. This means the list is now sorted!

Here's a conceptual representation of the Bubble Sort algorithm in pseudocode. Pseudocode is a way to describe an algorithm in a human-readable format that is independent of any specific programming language.

function bubbleSort(array):
  n = length of array
  for i from 0 to n-2:
    swapped = false
    for j from 0 to n-2-i:
      if array[j] > array[j+1]:
        swap array[j] and array[j+1]
        swapped = true
    if not swapped:
      break // Optimization: if no swaps, list is sorted
  return array

The outer loop (controlled by i) ensures we make enough passes to sort the entire list. The inner loop (controlled by j) performs the comparisons and swaps. The swapped flag is an optimization; if a full pass completes without any swaps, it means the list is already sorted, and we can stop early.