排序4个不带数组的数字 [英] Sort 4 numbers without array
本文介绍了排序4个不带数组的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个练习,需要将4个数字升序排列,然后不使用数组而降序.我只能使用循环和if语句.我已经用3个数字做到了,但是现在用4个数字我无法想到逻辑.
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;
}
推荐答案
一种进行固定大小的小型排序的好方法是使用分拣网络:
A nice way to do small, fixed-size sorts is using a 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; }
每行代码都对两个元素之间的比较和交换进行编码.
Each line codes a comparison and swap between two elements.
您可以使用此页面生成少量的最佳分类网络.输入.
You can use this page to generate optimal sorting networks for small numbers of inputs.
要以相反的顺序排序,只需将>
符号翻转为<
符号.
To sort in reverse order, just flip the >
signs to <
signs.
这篇关于排序4个不带数组的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文