1.Swap through pointers
BeginnerWrite void swap(int *a, int *b) and use it to sort three variables x = 9, y = 2, z = 5 into ascending order with at most three swaps.
Show hint
Compare and swap like a tiny bubble sort: (x, y), then (y, z), then (x, y) again.
Show solution
#include <stdio.h>
void swap(int *a, int *b) {
int t = *a;
*a = *b;
*b = t;
}
int main(void) {
int x = 9, y = 2, z = 5;
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;
}2 5 9