I've noticed a few questions in the Q&A forum lately on sorting an array. I only know the bubblesort 'off hand', so I give this to them, but this is hardly the best.
Searching on the site, there are some nice sorting functions, but it seems that all of them use functions like variable_local_array_get() or such.. these functions no longer exist in GM-S.
Actually, there is no way to pass an array to a script in GM. So these functions simply work to manipulate a 'myArray'.. it's up to you to replace it with your own array name.
So I've implemented some of the standard sorting algorithm's into GML.. and I'm posting it here, so that I can just send people here.
Here is what I've got.
-------------- The Code --------------
shuffle_array( size );
Spoiler
array_in_order( size )
Spoiler
simple_bubblesort - - Note.. this is not optimal, and is only included as it's simple, and easy to understand
Spoiler
bubblesort( size ) -- optimised ( should be )
Spoiler
bogosort -- Just a bit of fun. I saw this on wikipedia, and had to write it. (don't actually use it!)
Spoiler
insertion_sort( size )
Spoiler
quicksort( size ) -- quicksort is usually a recursive algorithm. However, GM-S does have a problem with recursion.. it can only go down to a depth of 32. Also, as a general rule recursion should be avoided in GM anyways. So here is an iterative implementation that I found, and implemented in GML..
Spoiler
mergesort() - a very fast sorting algorithm, which rivals quicksort..
Spoiler
heapsort() - again, a very quick sorting algorithm. Usually recursive, this script is the bottom-up implementation, which avoid that recursive behavior.
Spoiler
--------------The Rambling --------------
I haven't done any serious speed tests..( no numbers). But I quickly tried to sort a large array ( 1000 ).. it took the bubblesort's a second or so.. the insertion_sort was marginally faster. The quicksort() was very fast! Again, no actual numbers, but I'd estimate it's at least
What one should you use? Well, whichever one suits you. If you have a small array, just use a bubblesort.. it'll be fine. If you want to be a bit more adventurous, I believe insertion_sort is overall generally better than bubblesort.
If you have a large array, definitely go for the quicksort. If you have a VERY large array, use bogosort()



Find content
Male






