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.cvoid 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:
- If the array has fewer than 2 elements, return immediately.
- Walk the array comparing
tab[i]withtab[i + 1]. - If a pair is out of order, swap them using a
tempvariable and resetito 0 to restart the pass. - 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.