Home > algorithms > how to sort 3 values

how to sort 3 values

Problem
You have 3 values (e.g. three numbers), and you need to sort them. It could be a simple interview question to warm you up :)

Solution
The easiest way might be to use the good ol’ bubble sort. It can be done manually, without loops, since we only have three numbers.

Three values (let’s call them A, B, and C) are sorted, if A <= B <= C. Thus, the pseudo code to sort them is the following:

if A > B: swap(A, B)
if B > C: swap(B, C)    # the largest value is now in C
if A > B: swap(A, B)    # A and B are also sorted now

And now, let’s see it in C:

#include <stdio.h>

int main(int argc, char *argv[])
{
    int a = 8;
    int b = 7;
    int c = 6;
    int tmp;

    /* sort them in asc. order */
    if (a > b) {
        tmp = a; a = b; b = tmp;
    }
    if (b > c) {
        tmp = b; b = c; c = tmp;
    }
    if (a > b) {
        tmp = a; a = b; b = tmp;
    }

    /* print result */
    printf("%d <= %d <= %d\n", a, b, c);

    return 0;
}

Output:

6 <= 7 <= 8

Links

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: