tags:

views:

248

answers:

1

I'm using OpusScript, which is very similar to Javascript.

I need to sort an Array by two properties of the objects within it.

The object type of the array is 'ScoreEntity', with the properties Score and Time. I need the highest score at the 0 index of the array and vise versa, with the faster time overriding matching scores.

I've been trying to do this for ages and I cant get my head around it, I've got Saturday Syndrome!

ANSWER:

I used BubbleSort in the end, any comments on improving this are welcome.

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

}
+1  A: 

Did you choose an algorithm? (QuickSort is nice)

You have to define a comparison function determining which ScoreEntity is less (by comparing score and time) and then just implement the algorithm.

(I don't know OpusScript - Maybe you can just use a builtin sort which you tell the comparsion predicate)

Dario
No built in sort unfortunately. I'm aware of what I have to do, I just cant seem to write the logic down!
GenericTypeTea
Ah, sorry just found the actual QuickSort article, I'll try and convert the psuedo code.
GenericTypeTea
Thanks for pointing me in the right direction. I used BubbleSort in the end.
GenericTypeTea