I have an exercise where I need to put 4 numbers in ascending order and then descending without using arrays. I can only use loops and if statements. I\'ve
A nice way to do small, fixed-size sorts is using a sorting network:
int tmp;
if (a > b) { tmp = a; a = b; b = tmp; }
if (c > d) { tmp = c; c = d; d = tmp; }
if (a > c) { tmp = a; a = c; c = tmp; }
if (b > d) { tmp = b; b = d; d = tmp; }
if (b > c) { tmp = b; b = c; c = tmp; }
Each line codes a comparison and swap between two elements.
You can use this page to generate optimal sorting networks for small numbers of inputs.
To sort in reverse order, just flip the > signs to < signs.