想要按升序对数组进行排序,但Zero应为Last

时间:2017-07-06 07:12:19

标签: javascript

我正在为体育赛事做一个php应用程序,在某些情况下得分的最低值是赢家。就像100mt跑步赛事一样,胜利者是最快的跑步者。获胜者有完成比赛所需的最短时间。

但是我面对的是当有人缺席或在结束前退出然后我们提供得分零。在那种情况下,当我们要排序时,第一名将是ZERO。但那应该是最后的。

以下是我在javascript中的代码

var sorted = $(".result").sort(function (ib1, ib2) {
  return parseFloat($(ib2).val()) - parseFloat($(ib1).val());
});

// Result Names
$('#result_first').val($("#participant"+$(sorted.get(9)).data("section")).val());
$('#result_second').val($("#participant"+$(sorted.get(8)).data("section")).val());
$('#result_third').val($("#participant"+$(sorted.get(7)).data("section")).val());
$('#result_fourth').val($("#participant"+$(sorted.get(6)).data("section")).val());
$('#result_fifth').val($("#participant"+$(sorted.get(5)).data("section")).val());
$('#result_sixth').val($("#participant"+$(sorted.get(4)).data("section")).val());
$('#result_seventh').val($("#participant"+$(sorted.get(3)).data("section")).val());
$('#result_eighth').val($("#participant"+$(sorted.get(2)).data("section")).val());
$('#result_ninth').val($("#participant"+$(sorted.get(1)).data("section")).val());
$('#result_tenth').val($("#participant"+$(sorted.get(0)).data("section")).val());

// Result Numbers
$('#result_first_no').val($(sorted.get(9)).val());
$('#result_second_no').val($(sorted.get(8)).val());
$('#result_third_no').val($(sorted.get(7)).val());
$('#result_fourth_no').val($(sorted.get(6)).val());
$('#result_fifth_no').val($(sorted.get(5)).val());
$('#result_sixth_no').val($(sorted.get(4)).val());
$('#result_seventh_no').val($(sorted.get(3)).val());
$('#result_eighth_no').val($(sorted.get(2)).val());
$('#result_ninth_no').val($(sorted.get(1)).val());
$('#result_tenth_no').val($(sorted.get(0)).val());

请帮我排序这些值,ZERO值应该是最后的。

2 个答案:

答案 0 :(得分:4)

此处的基本想法是将#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #include <limits.h> int cmpfunc(const void *a,const void *b){ long long int x=((long long int *)a)[0]-((long long int *)b)[0]; if(x!=0){ return x; } return ((long long int *)a)[1]-((long long int *)b)[1]; } int main(int argc, char const *argv[]){ int n,i; scanf("%d",&n); long long a[n][2]; for(i=0;i<n;i=i+1){ scanf("%lld %lld",&a[i][0],&a[i][1]); } qsort(a,n,sizeof(a[0]),cmpfunc); for(i=0;i<n;i=i+1){ printf("%lld %lld\n",a[i][0],a[i][1]); } return 0; } 视为0

Infinity

一个简单的测试:

&#13;
&#13;
var sorted = $(".result").sort(function (ib1, ib2) {
    function value(el) {
        var x = parseFloat($(el).val());
        return x === 0 ? Infinity : x;
    }

    return value(ib2) - value(ib1);
});
&#13;
&#13;
&#13;

答案 1 :(得分:1)

$(".result").sort(function (ib1, ib2) {
    ib1 = parseFloat($(ib1).val()); ib2 = parseFloat($(ib2).val());
    return (ib1 * ib2 === 0) ? ((ib1 === ib2) ? (0) : ((ib1 === 0) ? -1 : 1)) : (ib2 - ib1);
});

如果ib1为0,那么它是&#34;更大&#34;比ib2。否则,如果他们的乘积为0(因此ib2为0),则ib1为&#34;较小&#34;比ib2。如果它们都不为0,则应用初始逻辑。