
/*

An example of how to sort arrys into alphanumerical order.
To do this I calculate the ASCII value of each alphanumeric character
and string of characters.

*/


DEF a[255]:string 
DEF b[255]:string 
DEF a1,a2,b1,b2,z1,z2:int 
DEF t1,t2:string
DEF myfile:file 
DEF position:int

'The array we want to sort
a[1] = "cit"
a[2] = "cat"
a[3] = "baaaaaa"
a[4] = "zaaaaaa"
a[5] = "abababa"
a[6] = "dog"
a[7] = "aaaaaa8"

'High value dummy needed for a last compare
'Could be set to 255 z's etc or CHR$(127) - DEL

a[8] = "zzzzzzzzzzzzzzzzzz" 
OPENCONSOLE

count = 7 'The number we want to sort

PRINT
PRINT "Original order of the arrays"
PRINT a[1],a[2],a[3],a[4],a[5],a[6],a[7]
PRINT
PRINT


'1st letter of the word sort e.g. (a)pple,(c)at,(d)og,(e)arth....(w)ater
'Sorts the words beginnig with A to Z

FOR x = 1 to count
FOR z = 1 to count

    length = 1
    position = 1
	GOSUB getval1  'get the ASCII value of first letter
    GOSUB checkltr 'sort them from words beginnig with A to Z

NEXT z
NEXT x


'1st letter sorted ok
PRINT "1st letter sort"
PRINT a[1]," ",a[2]," ",a[3]," ",a[4]," ",a[5]," ",a[6]," ",a[7]
PRINT

'Check subsequent letters of all array entries
'both single letters and strings of letters
LABEL totloop

FOR y = 1 TO count
FOR z = 1 to count

    length = 1
    position = 1 
    GOSUB getval1 

    FOR h = 2 TO LEN(a[z])

    IF LEN(a[z]) >= h

    IF b1 = b2 'letter match

		length = h
		position = 1 
		GOSUB getval1
        GOSUB checkltr 

    NEXT h

    ENDIF
    ENDIF

NEXT z
NEXT y


LABEL pr
PRINT
PRINT "Final alphbetical listing"
PRINT a[1]," ",a[2]," ",a[3]," ",a[4]," ",a[5]," ",a[6]," ",a[7]
PRINT 
PRINT "Press any key to exit..."

DO:UNTIL INKEY$ <> ""
CLOSEFILE myfile
END
 
SUB getval1 'Total up the ASCII values of each array for "g" positions 

a1 = 0
a2 = 0
b1 = 0
b2 = 0

FOR g = 1 TO length

a1 = ASC(LCASE$(MID$(a[z],g,1)))
b1 = b1 + a1 

a2 = ASC(LCASE$(MID$(a[z+1],g,1)))
b2 = b2 + a2

NEXT g

RETURN
ENDSUB

SUB checkltr() 

'Swap array entries over if needed 
'b1 & b2 hold the ASCII values of the current character or string of characters.

	IF b1 > b2 'To sort in decending order change to "b1 < b2"
	   t1 = a[z]
	   t2 = a[z+1]
	   a[z] = t2
	   a[z+1] = t1
	ENDIF 

RETURN 0
ENDSUB


