【问题标题】:Performing a manual sort on an Array对数组执行手动排序
【发布时间】:2010-10-26 18:03:28
【问题描述】:

我使用的是 OpusScript,它与 Javascript 非常相似。

我需要按数组中对象的两个属性对数组进行排序。

数组的对象类型是'ScoreEntity',具有Score 和Time 属性。我需要数组的 0 索引处的最高分,反之亦然,用更快的时间覆盖匹配分数。

我多年来一直在尝试这样做,但我无法理解它,我得了周六综合症!

回答:

我最终使用了 BubbleSort,欢迎任何改进此功能的 cmet。

function SortScoreArray(array)
{

    var unsorted = true
    while (unsorted)
    {

        // Tracks whether any changes were made, changed to false on any swap
        var complete = true
        for (var i = 0; i < array.length - 1; i++)
        {           

            // Holds the value for determining whether to swap the current positions
            var swap = false

            var currentItem = array[i]
            var nextItem = array[i + 1]

            if (currentItem.Score == nextItem.Score)
            {

                // The scores are the same, so sort by the time
                if (currentItem.Time > nextItem.Time)
                {
                    swap = true
                }

            }
            else if (currentItem.Score < nextItem.Score)
            {
                swap = true
            }


            if (swap)
            {
                array[i] = nextItem
                array[i + 1] = currentItem
                complete = false
            }

        }

        if (complete)
        {
            unsorted = false
        }

    }

    return array

}

【问题讨论】:

    标签: arrays sorting


    【解决方案1】:

    您是否选择了algorithm? (快速排序很好)

    您必须定义一个比较函数来确定哪个ScoreEntity 更小(通过比较分数和时间),然后执行算法。

    (我不知道 OpusScript - 也许你可以使用你告诉比较谓词的内置排序)

    【讨论】:

    • 不幸的是没有内置排序。我知道我必须做什么,但我似乎无法写下逻辑!
    • 啊,抱歉刚刚找到真正的快速排序文章,我会尝试转换伪代码。
    • 感谢您为我指明正确的方向。我最后使用了 BubbleSort。
    猜你喜欢
    • 2012-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-15
    • 2021-06-17
    相关资源
    最近更新 更多