Challenge: Sort Three with swap
Completed
Write void swap(int *a, int *b). Read three whole numbers into x, y, z and use swap to put them in order from smallest to biggest. Print them separated by spaces.
Input
Three integers.
Output
The three numbers in increasing order.
Example
Input
3 1 2
Output
1 2 3
Editor
C
Hints
Compare neighbours and swap them when they are in the wrong order.
Three compare-and-swap steps (x/y, y/z, x/y) are enough for three numbers.
Solution explanation
The first two steps push the biggest number to z; the last step orders x and y.
Show solution
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x, y, z;
scanf("%d %d %d", &x, &y, &z);
if (x > y) {
swap(&x, &y);
}
if (y > z) {
swap(&y, &z);
}
if (x > y) {
swap(&x, &y);
}
printf("%d %d %d\n", x, y, z);
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module