Raised This Month: $ Target: $400
 0% 

Example code for sorting an array


  
 
 
Thread Tools Display Modes
Prev Previous Post   Next Post Next
BAILOPAN
Join Date: Jan 2004
Old 06-15-2004 , 22:48  
Reply With Quote #5

Not to dis what you've done, as it is nice :] but you DID ask if there is a more efficient way ;]

What you both did is BubbleSort, the most inefficient way.

The best sorting algorithms are recursive, however recursion can cripple AMX's stack space very easily, so here is HeapSort.

Code. Note I am not sure if I'm passing 2D arrays right, it changed between 2.1 and 2.5. You may need to supply [24][] or [][SIZE] or [24][SIZE]
Code:
#define SIZE 32 new Strings[24][SIZE] //Quick reimplentation of strcmp().  is this necessary? stock fstrcmp(str1[], str2[]) {    new i = 0    for (i=0; i<SIZE; i++)    {       if (str1[i] != str2[i])       {          if (str1[i] > str2[i])             return 1          else             return -1       }    }    return 0 } HeapSort(Strings[][], xSize) {    new i, temp[SIZE]    new aSize = (xSize/2)-1    for (i = aSize; i >= 0; i--)    {       SiftDown(Strings, i, xSize)    }    for (i=xSize-1; i>=1; i--)    {       copy(temp, SIZE, Strings[0])       copy(Strings[0], SIZE, Strings[i])       copy(Strings[i], SIZE, temp)       SiftDown(Strings, 0, i-1)    } } SiftDown(Strings[][], root, bottom) {    new done, child, temp[SIZE]        done = 0    while ((root *2 <= bottom) && (!done))    {       if (root*2 == bottom) {          child = root * 2       } elseif (fstrcmp(Strings[root * 2], Strings[root * 2 + 1]) > 0) {          child = root * 2       } else {          child = root * 2 + 1       }       if (fstrcmp(Strings[root], Strings[child]) < 0)       {          copy(temp, SIZE, Strings[root])          copy(Strings[root], SIZE, Strings[child])          copy(Strings[child], SIZE, temp)          root = child       } else {          done = 1       }    } }
__________________
egg
BAILOPAN is offline
 



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT -4. The time now is 14:55.


Powered by vBulletin®
Copyright ©2000 - 2024, vBulletin Solutions, Inc.
Theme made by Freecode