data-structures · intermediate · ~15 min

Bubble sort

A simple O(n²) sort; understand its invariants.

Challenge

Sort an int array ascending in place by repeatedly swapping out-of-order adjacent pairs.

Task

Implement void bubble_sort(int *a, size_t n) that sorts the first n elements of a into ascending order, in place. No main — the grader calls it.

Input

  • a: pointer to a writable int array.
  • n: the number of elements (may be 0).

Output

Nothing is returned. After the call a[0..n-1] is sorted ascending.

Example

{3,1,2}          ->   {1,2,3}
{5,4,3,2,1}      ->   {1,2,3,4,5}
{2,2,1,1,3,3}    ->   {1,1,2,2,3,3}

Edge cases

  • Empty array (n = 0) and single-element arrays are already sorted.
  • Duplicates and negatives sort correctly.

Rules

  • Sort in place (no second array). Bubble sort is O(n^2); that is expected here.

Input format

Pointer a to a writable int array and a length n (n may be 0).

Output format

Nothing returned; a is sorted ascending in place.

Constraints

Sort in place; O(n^2) bubble sort is expected.

Starter code

#include <stddef.h>

void bubble_sort(int *a, size_t n) {
    /* TODO */
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.