在Windows Javascript应用程序中没有获得正确的排序数组

时间:2014-08-19 08:07:24

标签: javascript sorting windows-store-apps

在Windows应用商店应用(Javascript)中实现冒泡排序算法时,无法获得正确的排序输出。以下是Javascript的源代码: -

function BubbleSort()
{
    var numlist = NumList.value;
    var swap,flag=1,i=0;
    var ar = numlist.split(",");
    Val.value = ar[i];
    while(flag!=0)
    {
        for (var j = 0; j < ar.length; j++)
        {
           flag = 0;
            if(ar[j]>ar[j+1])
            {
                swap = ar[j + 1];
                ar[j + 1] = ar[j];
                ar[j] = swap;
                flag++;
            }
        }
    }
    IS.value = ar.toString();
}

输入: - &#34; 10,4,3,2,1,5,7,6,9&#34; 输出: - &#34; 10,3,2,1,4,5,6,7,9&#34;

我使用Visual Studio 2013 Update 3制作应用程序。你能告诉我出了什么问题吗?

1 个答案:

答案 0 :(得分:1)

尝试这样(根据您的需要调整):

function bubbleSort(v, desc)
{
    var ar = v.split(','), i = v.length;
    while((i-=1,i))
    {
        for (var j = 0; j < ar.length; j++)
        {
            if(desc ? +ar[j]<+ar[j+1] : +ar[j]>+ar[j+1]) //<= numeric comparison
            {
                var swap = ar[j];
                ar[j] = ar[j+1];
                ar[j+1] = swap;
            }
        }
    }
    return ar.join();
}
// usage asc en desc:
bubbleSort('10,4,3,2,1,5,7,6,9');       //=> [1,2,3,4,5,6,7,9,10]
bubbleSort('10,4,3,2,1,5,7,6,9', true); //=> [10,9,7,6,5,4,3,2,1]