data-structures · intermediate · ~15 min
A simple O(n²) sort; understand its invariants.
Sort an int array ascending in place by repeatedly swapping out-of-order adjacent pairs.
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.
a: pointer to a writable int array.n: the number of elements (may be 0).Nothing is returned. After the call a[0..n-1] is sorted ascending.
{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}
n = 0) and single-element arrays are already sorted.Pointer a to a writable int array and a length n (n may be 0).
Nothing returned; a is sorted ascending in place.
Sort in place; O(n^2) bubble sort is expected.
#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.