Course contentsShow
← C
Lesson 1047 of 1,21914. Data Structures in CFree lesson

Bubble Sort: The swap logic

Bubble Sort: The swap logic

What you'll learn: How to exchange the positions of two adjacent elements in an array if they are in the wrong order.

The "Tallest Student" Analogy

Imagine a line of five students standing side-by-side. You want to arrange them from shortest to tallest. You start at the left and look at the first two students. If the person on the left is taller than the person on the right, they are out of order. To fix this, they must swap places.

In C, we call this a comparison and swap. You move down the line, comparing pairs (1st and 2nd, then 2nd and 3rd, and so on). By the time you reach the end of the line, the "tallest" student will have "bubbled" up to the very last position.

Why we need a "Temporary" Variable

Swapping two values in a computer isn't as simple as hands crossing in mid-air. If you have two variables, a and b, and you try to swap them by saying a = b;, you just erased the original value of a forever. Both now hold b's value.

To prevent this, we use a temporary container. Think of it like having a glass of orange juice and a glass of milk. To swap them, you need an empty third glass. You pour the juice into the third glass, pour the milk into the juice glass, and finally pour the juice from the third glass into the milk glass.

The Code Implementation

In a Bubble Sort, we perform this swap inside an if statement that checks if the left element is greater than the right element.

int arr[] = {5, 2, 8, 1, 3};
int i = 0; // Current position

// Compare the current element with the next one
if (arr[i] > arr[i + 1]) {
    // 1. Save the left value in a temporary 'container'
    int temp = arr[i];
    
    // 2. Move the right value into the left spot
    arr[i] = arr[i + 1];
    
    // 3. Move the saved value from 'temp' into the right spot
    arr[i + 1] = temp;
}

How this builds the sort

By repeating this logic across the entire array, the largest numbers gradually migrate to the end. The "swap" is the engine of the Bubble Sort; without that temporary variable to hold the data during the transition, the values would overwrite each other and your data would be lost.

Key takeaway

A swap requires a temporary variable to act as a placeholder so that no data is overwritten during the exchange.