Lesson 26 of 31

Sorting

Sorting

Sorting is one of the most fundamental algorithms in computer science. Let's implement bubble sort, a simple sorting algorithm.

How Bubble Sort Works

Bubble sort repeatedly steps through the array, compares adjacent elements, and swaps them if they're in the wrong order. After each pass, the largest unsorted element "bubbles up" to its correct position.

Pass 1: [5, 3, 8, 1] → [3, 5, 1, 8]   (8 is in place)
Pass 2: [3, 5, 1, 8] → [3, 1, 5, 8]   (5 is in place)
Pass 3: [3, 1, 5, 8] → [1, 3, 5, 8]   (done!)

Implementation

void bubble_sort(int *arr, int n) {
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                // Swap
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

The universal translator processes languages one pair at a time, comparing and rearranging until everything is in order. Bubble sort works the same way.

Swapping Elements

The swap pattern is essential in many algorithms:

int temp = a;
a = b;
b = temp;

Printing an Array

A helper to print arrays is handy for debugging:

void print_array(int *arr, int n) {
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}

Your Task

Implement void bubble_sort(int *arr, int n) that sorts an array of n integers in ascending order. Sort and print two arrays: {5, 3, 8, 1, 9} and {10, 4, 7, 2}.

TCC compiler loading...
Loading...
Click "Run" to execute your code.