排序4个数字没有数组

时间:2014-07-31 23:25:58

标签: java sorting

我有一个练习,我需要按升序排列4个数字,然后在不使用数组的情况下降序 。我只能使用循环和if语句。我已经完成了3个数字,但现在有4个数字,我无法想到逻辑。

  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;
  }

1 个答案:

答案 0 :(得分:14)

使用sorting network

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; }

您可以使用this page为少量输入生成最佳排序网络。