【发布时间】: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
}
【问题讨论】: