Skip to main content

sort_int_tab — Sort Integer Array

Allowed functions: none

It must sort (in-place) the tab int array, that contains exactly size members, in ascending order. Doubles must be preserved. Input is always coherent.

void sort_int_tab(int *tab, unsigned int size);

Solution

Download sort_int_tab.c
void sort_int_tab(int *tab, unsigned int size) {
unsigned int i;
int temp;

if (size < 2)
return;
i = 0;
while (i < size - 1) {
if (tab[i] > tab[i + 1]) {
temp = tab[i];
tab[i] = tab[i + 1];
tab[i + 1] = temp;
i = 0;
} else
i++;
}
}

How It Works

Goal: Sort an integer array in ascending order, in place.

Approach: Bubble sort — compare adjacent elements, swap if out of order, and restart from the beginning on each swap.

Step by step:

  1. If the array has fewer than 2 elements, return immediately.
  2. Walk the array comparing tab[i] with tab[i + 1].
  3. If a pair is out of order, swap them using a temp variable and reset i to 0 to restart the pass.
  4. If no swap is needed, advance i. The loop ends when a full pass completes with no swaps.

Key concept: Bubble sort algorithm — repeatedly swapping adjacent out-of-order elements until the array is sorted.