Array sorting and shuffling

These functions will be added in ACSUtils 1.8.0

SortArray

void SortArray(int begin, int end, str lt, str swap)

Sorts an array with indices in range [begin, end). lt and swap are script names.

script “lt” (int a, int b) must return the result of array[a] < array[b] using SetReturnValue. If you return array[a] > array[b], sorting order is reversed.

script “swap” (int a, int b) must swap array[a] with array[b].

Example: sorting a simple array of numbers:

int array[10];
script "compare_two_elements" (int a, int b)
{
SetResultValue(array[a] < array[b]);
}
script "swap_two_elements" (int a, int b)
{
int temp = array[a];
array[a] = array[b];
array[b] = temp;
}
function void SortTheArray(void)
{
SortArray(0, 10, "compare_two_elements", "swap_two_elements");
// You can also sort sub-arrays:
SortArray(3, 8, "compare_two_elements", "swap_two_elements");
}

Example: making a scoreboard sorted by score:

int Players[MAX_PLAYERS];
int PlayerScores[MAX_PLAYERS];
int NumPlayers;
script "lt" (int a, int b)
{
SetResultValue(PlayerScores[a] > PlayerScores[b]);
}
script "swap" (int a, int b)
{
swap(Players[a], Players[b]);
Players[a] = r1;
Players[b] = r2;
swap(PlayerScores[a], PlayerScores[b]);
PlayerScores[a] = r1;
PlayerScores[b] = r2;
}
function void BuildScoreboard(void)
{
// Fill scoreboard without sorting
for (int player = 0; player < MAX_PLAYERS; player++)
{
if (PlayerInGame(player))
continue;
Players[NumPlayers] = player;
PlayerScores[NumPlayers] = GET_PLAYER_SCORE(player);
NumPlayers++;
}
// Sort it by score
SortArray(0, NumPlayers, "lt", "swap");
}