Sorting an array according to Priotity value - Printable Version
+- SA-MP Forums Archive (
https://sampforum.blast.hk)
+-- Forum: SA-MP Scripting and Plugins (
https://sampforum.blast.hk/forumdisplay.php?fid=8)
+--- Forum: Scripting Help (
https://sampforum.blast.hk/forumdisplay.php?fid=12)
+--- Thread: Sorting an array according to Priotity value (
/showthread.php?tid=605609)
Sorting an array according to Priotity value -
Amads - 22.04.2016
Hello.
I've been trying to implement array sorting but so far I can't wrap my head around it.
PHP код:
#define MAX_ITEMS 20
new Items[MAX_ITEMS];
Somewhere in the code there is a function which returns Priority according to value of the array:
PHP код:
ItemPriority(ItemID)
{
new Priority;
switch(ItemID)
{
case 1: Priority = 1;
case 2: Priority = 2;
case 3: Priority = 2;
case 4: Priority = 2;
case 5: Priority = 1;
case 6: Priority = 2;
case 7: Priority = 3;
case 8: Priority = 2;
}
return Priority;
}
And now, how can I sort an array so first there are items with Priority 1, then 2, etc?
Example array before sorting:
PHP код:
Items[0] = 3; // Priority = 2
Items[1] = 7; // Priority = 3
Items[2] = 1; // Priority = 1
Items[3] = 5; // Priority = 1
and after:
PHP код:
Items[0] = 1; // Priority = 1
Items[1] = 5; // Priority = 1
Items[2] = 3; // Priority = 2
Items[3] = 7; // Priority = 3
Anyone?
Re: Sorting an array according to Priotity value -
DTV - 22.04.2016
EDIT: Realized this wouldn't fix anything related to the problem, sorry
Re: Sorting an array according to Priotity value -
Amads - 23.04.2016
bump
Re: Sorting an array according to Priotity value -
Nero_3D - 23.04.2016
A little insertion sort for small arrays should do the job
PHP код:
stock InsertionSortItem(array[], size = sizeof array) {
new
i,
j,
value,
priority
;
while(i < size) {
priority = ItemPriority((value = array[i]));
for(j = i - 1; j >= 0 && ItemPriority(array[j]) > priority; --j) {
array[j + 1] = array[j];
}
array[j + 1] = value;
i++;
}
}
You should add a default value of invalid items
PHP код:
ItemPriority(ItemID)
{
new Priority = cellmax;
//...