Simpler way of sorting three numbers

Call the three variables x, y, and z, then:

if (x > y) swap(x, y);
if (y > z) swap(y, z)
if (x > y) swap(x, y);

Writing the swap function is left as an exercise for the reader. Hint: you may have to use pointers.


If you want to sort the values into new external variables, you can actually do the swaps without temporaries:

void sort(int a, int b, int c, int *min, int *mid, int *max) {
    min = a;
    mid = b;
    max = c;
    if (min > mid) { mid = a; min = b; }
    if (mid > max)
    {
        max = mid;
        mid = c;
        if (min > mid)
        {
            mid = min;
            min = c;
        }
    }
}

This works because the last swap test is really only needed if the second test succeeds (otherwise it will simply be a repetition of the first test, which will fail by definition since we already sorted those variables).

Because of this, we can track the assignments of each of the original variables and avoid swap locals.


if (a > c)
   swap(a, c);

if (a > b)
   swap(a, b);

//Now the smallest element is the 1st one. Just check the 2nd and 3rd

if (b > c)
   swap(b, c);

Note: Swap changes the values of two variables.


#include <stdio.h>
#define min(a,b) ((a)<(b)?(a):(b))
#define max(a,b) ((a)>(b)?(a):(b))
int main(){
   int a, b, c;
   int hi;
   int lo;

   printf("Enter No. 1: ");
   scanf("%d", &a);
   printf("Enter No. 2: ");
   scanf("%d", &b);         
   printf("Enter No. 3: ");
   scanf("%d", &c);

   lo = min(min(a, b), c);
   hi = max(max(a, b), c);
   printf("LOWEST %d\n", lo);
   printf("MIDDLE %d\n", a+b+c-lo-hi);
   printf("HIGHEST %d\n", hi);  

   getchar(); 
}    

Tags:

C