## Numerics and string sorting

Henko
Posts: 793
Joined: Tue Apr 09, 2013 12:23 pm
My devices: iPhone,iPad
Windows
Location: Groningen, Netherlands
Flag:

### Numerics and string sorting

option base 1
dim a(50),tex\$(10)
dim cities\$(28)
for i=1 to 26
read cities\$(i)
next i
data "ulm","vancouver","warschau","xnotfound","yosemite"
data "kano","london","moskow","nairobi","osaka"
data "fremont","groningen","helsinki","inverness","jakarta"
data "proletarskiy","quatar","riad","sydney","tunis"
data "amsterdam","bangkok","caracas","dublin","edinburgh"
data "zaragoza"
n=10
for i=1 to n ! a(i)=rnd(99) ! print a(i) ! next i
nsort(a,n)
print
for i=1 to n ! print a(i) ! next i
print
for i=1 to 26 ! print i,cities\$(i) ! next i
asort(cities\$,26)
print
for i=1 to 26 ! print i,cities\$(i) ! next i
end

' numbers sort (method: insert sort)
'
def nsort(a(),n)
for i=2 to n
if a(i)>a(i-1) then loop2
res=a(i)
for j=i-1 to 1 step -1
if a(j)<res then loop1
a(j+1)=a(j)
next j
loop1:
a(j+1)=res
loop2:
next i
end def

' string sort (method: insert sort)
'
def asort(a\$(),n)
for i=2 to n
if str_cmp(a\$(i),a\$(i-1))=1 then loopa2
res\$=a\$(i)
for j=i-1 to 1 step -1
if str_cmp(a\$(j),res\$)=2 then loopa1
a\$(j+1)=a\$(j)
next j
loopa1:
a\$(j+1)=res\$
loopa2:
next i
end def

' string compare returns:
'  0 : strings are identical
'  1 : string a\$ greater than string b\$
'  2 : b\$ greater than a\$
'
' c\$ must be extended if other caracters may be encounterd in strings
'     (for instance capitals)
'
def str_cmp (a\$,b\$)
c\$=" !'-./0123456789?@abcdefghijklmnopqrstuvwxyz"
la=len(a\$) ! lb=len(b\$)
if a\$=b\$ and la=lb then
str_cmp=0 ! return
end if
min=la ! if lb<min then min=lb
for i=1 to min
as\$=substr\$(a\$,i,i) ! bs\$=substr\$(b\$,i,i)
if as\$=bs\$ then goto volg
for k=1 to 44
if as\$=substr\$(c\$,k,k) then
str_cmp=2 ! return
end if
if bs\$=substr\$(c\$,k,k) then
str_cmp=1 ! return
end if
next k
volg:
next i
if min=la then str_cmp=2 else str_cmp=1
end def