Javascript中的排序算法 [英] Sorting algorithm in Javascript
问题描述
为jQuery函数
$("#sort").click
写一个JavaScript回调.允许用户以任何顺序输入三个数字.按从低到高的顺序输出数字.
Write a JavaScript callback for the jQuery function
$("#sort").click
. Allow the user to enter three numbers in any order. Output the numbers in order from lowest to highest.
$(document).ready(function() {
$("#sort").click(function() {
var a = Number($("#a").val());
var b = Number($("#b").val());
var c = Number($("#c").val());
var message = "";
if (b > c) {
if ((b + c) > (a + c)) {
message = c + " " + a + " " + b;
} else {
message = c + " " + b + " " + a;
}
} else {
message = b + " " + a + " " + c;
}
if (b > a) {
if ((a + b) > (a + c)) {
message = a + " " + c + " " + b;
} else {
message = a + " " + b + " " + c;
}
} else {
message = b + " " + c + " " + a;
}
$("#output").html(message)
});
});
任何人都介意看一下这段代码并说出什么问题吗?
Would anyone mind looking at this code and saying what's wrong?
推荐答案
这里有一些很棒的jQuery答案,我将介绍比较部分.
Some great jQuery answers here, I'll cover the comparisons part.
您不需要进行五次比较,只需进行三次比较(如果幸运的话就可以进行两次).比较a
和b
,并交换a > b
.然后比较c
和b
.如果为c > b
,则说明已完成,否则请比较c
和a
:
You don't need five comparisons, just three (or two if you're lucky). Compare a
and b
, and swap them if a > b
. Then compare c
and b
. If c > b
, you're done, otherwise compare c
and a
:
if (a > b)
x = a, a = b, b = x;
if (c < b)
if (c < a)
result = [c, a, b];
else
result = [a, c, b];
else
result = [a, b, c];
如果所有数字均为32位正整数,则可以对它们进行排序,而无需进行任何比较:
If all numbers are 32-bit positive ints, you can sort them without any comparisons at all:
min = function(a,b) { return b + ((a-b) & ((a-b)>>31)) }
max = function(a,b) { return a - ((a-b) & ((a-b)>>31)) }
x = min(a, min(b, c));
z = max(a, max(b, c));
y = (a + b + c) - (x + z);
result = [x, y, z];
这篇关于Javascript中的排序算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!