data-structures · intermediate · ~15 min
Implement a simple comparison sort.
Sort an array in place using bubble sort.
Implement void bubble_sort(int *a, int n) that sorts the first n elements of a into ascending order, modifying the array in place.
a: a writable array of at least n ints.n: the number of elements to sort (n >= 0).Nothing returned; a[0..n-1] is rearranged into non-decreasing order.
{3,1,2} -> {1,2,3}
{5,4,3,2,1} -> {1,2,3,4,5}
{1} -> {1}
n == 0 or n == 1: nothing to do.a: writable array of at least n ints; n: element count (>= 0).
Nothing returned; a[0..n-1] is sorted ascending in place.
Sort in place by swapping adjacent out-of-order elements.
void bubble_sort(int *a, int n) {
/* TODO */
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.