Performing a manual sort on an array
I am using OpusScript which is very similar to Javascript.
I need to sort an array by two properties of the objects inside it.
The array object type is "ScoreEntity" with the Score and Time properties. I need the highest score at index 0 of the array, and vice versa, with faster times exceeding matching scores.
I've been trying to do this for ages and I can't get around it, I have Saturday syndrome!
ANSWER:
In the end I used BubbleSort, any comments on improving this are appreciated.
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
}
a source to share
Did you choose algorithm ? (QuickSort is good)
You have to define a comparison function that determines which is ScoreEntity
smaller (by comparing the score and time) and then just implement the algorithm.
(I don't know OpusScript - Maybe you can just use the built-in type you tell the comparison predicate)
a source to share