Bubble Sort Algorithm

How the Bubble Sort Algorithm Works

Anirudh Dattu
2 min readOct 6, 2023

Imagine you have a list of numbers that you want to sort from smallest to largest. You start at the beginning of the list and compare the first two numbers. If the first number is larger than the second, you swap them. If not, you leave them as they are.

Let us start with an Example.

Initial List: We start with the unsorted list: 5, 3, 1, 4, 2.

Pass 1: In the first pass, we compare adjacent numbers in the list and swap them if they are in the wrong order. We begin with the first pair, which is 5 and 3. Since 5 is greater than 3, we swap them, resulting in 3, 5, 1, 4, 2. We continue this process for the rest of the list, moving from left to right.

You continue this process, moving one position to the right each time, comparing and swapping adjacent numbers as needed. Each pass through the list will ensure that the largest unsorted number “bubbles up” to the end of the list.

Pass 2: In the second pass, we repeat the process. Now, the largest number (5) is at the end of the list, and we don’t need to touch it. We compare 3 and 1, swap them, and continue with the rest of the list: 3, 1, 4, 2, 5.

You repeat these passes through the list until you make a pass where no swaps are needed. This means that all the numbers are in their correct positions, and your list is sorted.

After the last pass, the Bubble Sort algorithm has fully sorted the list in ascending order. The key idea is to compare adjacent elements and swap them if they are in the wrong order and repeat this process until no more swaps are required, indicating that the list is sorted. Bubble Sort is straightforward but may not be the most efficient for large lists.

--

--

No responses yet