java 对没有数组的 4 个数字进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25070577/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sort 4 numbers without array
提问by user3500017
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.
我有一个练习,我需要将 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;
}
回答by Boann
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; }
You can use this pageto generate optimal sorting networks for small numbers of inputs.
您可以使用此页面为少量输入生成最佳排序网络。