Jump to content

Anyone got an efficient array sort function? (for depth sorting sprites)


rich
 Share

Recommended Posts

I'm trying to sort an array of sprites based on their y value. The item at the start of the array is drawn first (so at the 'back' of the display list)

 

Lots of sprites will have the same y value, in which case they should not be moved anywhere in the array. For this reason you can't use the native Array.sort (unless there is a compare function I've not yet tested that solves it?) as when items are equal they are shuffled around at will, causing them to constantly flicker as they all swap depths.

 

So.. anyone got some code they could contribute that solves this? :)

Link to comment
Share on other sites



children.sort(function(a,{  
    if (a.position.y > b.position.y) {
        return 1;
    }
    if (a.position.y < b.position.y) {
        return -1;
    }
    return 0;
});


 

This doesn't work?

 

Same value should stay untouched.

Link to comment
Share on other sites

I don't have an exact answer for you, but something to look into might be an insertion sort. I've been meaning to try this out because it's supposedly pretty fast for sets that are already mostly sorted and is stable (equal items don't swap).

 

Edit: Our current sorting works like you've mentioned above. We assign IDs to each renderable object upon creation and sub-sort based on that if the depth values are equal:

function (a,  {  return (a.z === b.z) ? (a.id - b.id) : (a.z - b.z);}
Link to comment
Share on other sites

You can choose stable sort with better performance than insertion sort O(n2). Almighty wikipedia: Comparison of algorithms :)

You can hardly find better algo than insertion sort for nearly sorted arrays. Also it always depends on many things and you can't say really until you test it. Looking just at O complexity will not be very precise. Also you will implement insert sort much faster than say heap sort.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...