Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 done it with 3 numbers, but now with 4 numbers I am unable to think of the logic.

  float great1 = 0, great2 = 0, great3 = 0, great4 = 0;
  int a = 7, b = 5, c = 6, d = 0;

  // Descending
  if (a > b && b > c) {
    great1 = a;
    great2 = b;
    great3 = c;

  } else if (a > b && b < c) {
    great1 = a;
    great2 = c;
    great3 = b;

  } else if (b > a && a > c) {
    great1 = b;
    great2 = a;
    great3 = c;

  } else if (b > a && a < c) {
    great1 = b;
    great2 = c;
    great3 = a;

  } else if (c > a && a > b) {
    great1 = c;
    great2 = a;
    great3 = b;
  }

  else {
    great1 = c;
    great2 = b;
    great3 = a;
  }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
183 views
Welcome To Ask or Share your Answers For Others

1 Answer

A nice way to sort a small, fixed size of inputs is using a sorting network.

This network sorts 4 elements:

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 does a comparison and swap between two elements.

If you want to sort in reverse order, just flip the > signs to < signs.

Links:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...