data-structures · intermediate · ~15 min

Bubble sort

Implement a simple comparison sort.

Challenge

Sort an array in place using bubble sort.

Task

Implement void bubble_sort(int *a, int n) that sorts the first n elements of a into ascending order, modifying the array in place.

Input

  • a: a writable array of at least n ints.
  • n: the number of elements to sort (n >= 0).

Output

Nothing returned; a[0..n-1] is rearranged into non-decreasing order.

Example

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

Edge cases

  • n == 0 or n == 1: nothing to do.
  • Already-sorted input stays sorted.

Input format

a: writable array of at least n ints; n: element count (>= 0).

Output format

Nothing returned; a[0..n-1] is sorted ascending in place.

Constraints

Sort in place by swapping adjacent out-of-order elements.

Starter code

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.