Page 1 of 1

Sorting a string

Posted: Mon May 12, 2003 8:54 am
by rominfo
hello everone

I currently writing a programm for processing string, my problem is sorting a string, with len 30 char max, quickly.

thanks... 8O

my firts procedure...

Posted: Mon May 12, 2003 7:38 pm
by rominfo
The procedure CharSort is :

Code: Select all

Procedure CharSort(pVar, lNoDup)
    Protected cSort.s, nCiclo.b, nLenS.b

    cSort = PeekS(pVar)
    nLenS = Len(cSort)
    Dim aSort.s(nLenS)
    For nCiclo = 1 To nLenS
        aSort(nCiclo) = Mid(cSort, nCiclo, 1)
    Next

    ; sort array...
    SortArray(aSort(), 0)

    ; passing result to original string...
    cSort = ""
    For nCiclo = 1 To nLenS
        cSort + aSort(nCiclo)
    Next
    PokeS(pVar, cSort)
EndProcedure

; test procedure...
cNum.s = "PUREBASIC TEST"
DEBUG cNum
CharSort(@cNum, 0)
DEBUG cNum
I need fast procedure. Thanks...

Posted: Mon May 12, 2003 8:35 pm
by freak
Ah, now i understand what you mean by 'sort a string' :)
Here's a little improovment...

With some Memory routines, you can avoid all those PeekS/PokeS,
and all the For/Next Loops.

The trick is to copy the whole string to an array of bytes, so each
byte holds one string, then you can soret that, and copy the
string back.

lstrlen_(pVar) is a WinAPI command, if you have the Demo, this will
not work, use the commented line below in this case.

Code: Select all

Procedure CharSort(pVar, lNoDup) 
  Protected nLenS.l
  
  nLenS = lstrlen_(pVar)  ; get length: API version, string doesn't have to be peeked
  ; nLenS = Len(PeekS(pVer))  ; PB version, PeekS needed.
  
  Dim aSort.b(nLenS-1)  ; define Array of bytes, so each byte holds one character
                        ; nLenS-1 because PB Dims from 0 to the given boundary, making exactly
                        ; nLenS+1 members, and then this method doesn't work, because there
                        ; will be one byte holding 0, which will be sorted to the front,
                        ; resulting in an empty string then.
  
  CopyMemory(pVar, @aSort(), nLenS)  ; fill array with string characters
  SortArray(aSort(), 0)              ; sort array
  CopyMemory(@aSort(), pVar, nLenS)  ; copy sorted string back to source
  
EndProcedure 

; test procedure... 
cNum.s = "PUREBASIC TEST" 
Debug cNum 
CharSort(@cNum, 0) 
Debug cNum 
btw: what is the ' lNoDup' parameter of the procedure for?

Timo

Posted: Mon May 12, 2003 11:26 pm
by tinman
freak wrote:btw: what is the ' lNoDup' parameter of the procedure for?
flag for no duplicates?

The routine could probably be made faster by using a sort routine which took the length of the array. It would then not require any memory copying. (Don't try it with my sort code from the resources site, Fred's asm code kicks its ass even when having to do all those copies ;)

Thanks...

Posted: Tue May 13, 2003 8:42 am
by rominfo
Thanks freak for your improvement... :lol: