I am working with Game Maker Studio 2.3.6 to sort the list of character speeds on screen in descending order with an iterative algorithm (bubble sort). However, I plan to have a lot of on-screen characters for some of the battles. Therefore, I considered switching to the quicksort algorithm to reduce run time.
Here is the simple iterative algorithm I currently use to sort the speed values (written in GML).
function bubble_sort(list){
list_size = ds_list_size(list);
for (var i = 0; i < list_size; i++) {
for (var j = 0; j < list_size - i - 1; j++) {
if (list[|j].current[@SPEED] < list[|j+1].current[@SPEED]) {
var swapped = list[|j];
list[|j] = list[|j+1];
list[|j+1] = swapped;
}
}
}
}
I defined the speed values using macros.
#macro SPEED 0
base[SPEED] = 10;
current[SPEED] = base[@SPEED];
When I call my bubble sort function, I use global.units
as an argument which is a list that contains the IDs of all the mobs that have been spawned. Through global.units
, one can access their speed with .current[@SPEED]
for a j-th mob as you can see in the bubble sorting algorithm above.
I wrote a quicksort algorithm. Below are the partition and the function itself.
function partition(list, low, high){
var pivot = list[high]; // point de pivot autour duquel il faut modifier la liste
var i = low;
for (j = low + 1; j <= high; j++) {
if (list[j] > pivot) {
i++;
// on fait pivoter la liste en i et la liste en j
swapped = list[i];
list[@i] = list[j];
list[@j] = swapped;
}
}
// on fait pivoter la liste en i+1 avec la plus haute valeur
swapped = list[i];
list[@i] = list[high];
list[@high] = swapped;
return i;
}
In a different script,
function quicksort(list, low, high) {
if (low < high) {
partition_ref = partition(list, low, high); // on partitionne l'indice
// on trie les éléments de manière récursive avant et après la phase de partition des éléments
quicksort(list, low, partition_ref);
quicksort(list, partition_ref + 1, high);
}
}
After a lot of head-scratching, I could not work out how I can implement the SPEED macro into my quicksort algorithm. Perhaps this is one of those problems with obvious answers, but which I cannot see.
Could anyone give me a hand?
The general options related to utilizing what's already is in the language (and is written in native code rather than slightly-slower GML) are:
array_sort
with a custom comparator functionds_grid
along with their "score" and use ds_grid_sort
(score << 32) | id
in a ds_list and use ds_list_sort
(if the source list/array contains structs, use an index inside that instead).As for your quicksort, var pivot = list[high]
and if (list[j] > pivot) {
would need to account for the item's score (speed) rather than getting/comparing it "as is".