PDA

View Full Version : Sorting an Array



Melanie
- 16th November 2003, 11:25
How can I sort an array? In case anyone wants one way of doing it here's a ready to run example...

CounterA var BYTE
DataTemp var WORD
MyData var WORD[12]

SortArray subroutine sorts the example 12 element MyData array in sequence placing the smallest value into MyData[0] and the largest value into MyData[11]...

SortArray:
CounterA=0
SortArrayLoop:
If MyData[CounterA+1] < MyData[CounterA] then
DataTemp=MyData[CounterA]
MyData[CounterA]=MyData[CounterA+1]
MyData[CounterA+1]=DataTemp
If CounterA>0 then CounterA=CounterA-2
endif
CounterA=CounterA+1
If CounterA<11 then goto SortArrayLoop
Return

By changing the <11 in the line above, you can sort whatever size of array you've got. The value is arraysize-1, so <24 will sort a 25 element array. Just redefine WORDS to BYTES if you want an 8-bit sort routine.

A routine like this could be much simplified if MeLabs could get SWAP to work on variable index arrays... perhaps a future suggestion.

Melanie

Melanie
- 2nd March 2004, 15:43
First appologies to the 179 people who viewed the above thread...

I have discovered that if you post on this forum a left square bracket ] immediately followed by a less-than sign < then it calls strange Masonic rites, invokes an end-of-the-world scenario and corrupts your posting. Leaving spaces between them ensures continuance of the world as we know it. Many thanks to Marcos for pointing out the error. Teaches me to read what I post instead of assuming when you press Send it actually comes out the other end the way you expected.

The above posting now shows the code CORRECTLY.

Melanie