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.