Home AMX User Forum AMX General Discussion

Array Sorting

Hi Guys,

Does anyone know the best way, with NetLinx, to sort an Array? For example;

Sort[] = {'aaa','adc','abb','aab','acc'} = {'aaa','aab','abb','acc','adc'}
OR
Sort[] = {1,5,3,4} = {1,3,4,5}

I could attempt to write it but my life would be easier if someone has already written it :)

Thanks,

C

Comments

  • CameronCameron Posts: 56
    Got it, just need to change the sort order - here is a sample for anyone else;
    DEFINE_FUNCTION fnSortAddressBook()
    {
    	STACK_VAR INTEGER 	nSwapped
    	STACK_VAR INTEGER 	nCount
    	STACK_VAR CHAR		cTempName[50]
    	STACK_VAR CHAR		cTempAddress[50]
    
    	nSwapped = TRUE
    
    	WHILE(nSwapped = TRUE)
    	{			
    		nSwapped = FALSE
    
    		FOR(nCount = 2; nCount <= nAddressBookEntries; nCount++) // This is = to 2 as we have no 0 in NetLinx arrays
    		{
    			IF(cAddressBookNames[nCount - 1] > cAddressBookNames[nCount])
    			{
    				cTempName = cAddressBookNames[nCount]
    				cTempAddress = cAddressBookAddresses[nCount]
    
    				cAddressBookNames[nCount] = cAddressBookNames[nCount - 1]
    				cAddressBookNames[nCount - 1] = cTempName
    
    				cAddressBookAddresses[nCount] = cAddressBookAddresses[nCount - 1]
    				cAddressBookAddresses[nCount - 1] = cTempAddress
    
    				nSwapped = TRUE
    			}
    		}
    	}
    }
    
  • mighemighe Posts: 39
    It is not a good idea reinventing a sorting algorithm.
    An efficient sorting algorithm can solve the problem in N logN time and a simple one can solve it N^2.
    Your nRunCount variable seems to says 'I'm reinventing the wheel. The square wheel'.

    You can easily implement a selection sort or an insertion sort if you can accept a quadratic execution time, otherwise a merge sort or a quicksort.

    Usually in netlinx we have small arrays (length << 1000), so one of the first two algorithms is enough and very very simple to implement
  • ijedijed Posts: 28
    this seems appropriate:

    http://xkcd.com/1185/

    Kim has handy functions on his github - array.axi has a quicksort algorithm you could adapt for multi-dimensional arrays:

    https://github.com/KimBurgess/netlinx-common-libraries
Sign In or Register to comment.