Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Argument starter - The roots of all evil
Message
De
10/09/2004 10:02:29
Walter Meester
HoogkarspelPays-Bas
 
Information générale
Forum:
Visual FoxPro
Catégorie:
Codage, syntaxe et commandes
Divers
Thread ID:
00938079
Message ID:
00941031
Vues:
54
Hi George,

I really love those challenges. Though I also have one that uses recursion, the following seems to be most effective (And readable).
FUNCTION SearchArray(aArray, cSearchValue)
LOCAL nStart, nEnd, nIndex, nFound

nStart = 1
nEnd = ALEN(aArray,1)
nFound = 0

DO WHILE nStart =< nEnd AND nFound = 0
	nIndex = INT((nStart + nEnd) /2)
	DO CASE
		CASE aArray[nIndex] = cSearchValue
			nFound = nIndex
			
		CASE aArray[nIndex] > cSearchValue
			nEnd = nIndex - 1
			
		OTHERWISE
			nStart = nIndex + 1
	ENDCASE
ENDDO
RETURN nFound
Walter,



>>Thanks, Tamar
>>
>>That's exactly as I learnt it and understood it (if you read my question then I roughly described it thus). OK I was interested in how George would do that in a do while loop.
>>
>>Terry
>>
>>>>... As I learnt it in college it means going backward and foreward in the list, halving the distance as you go (in essence). If that's so, please could you indicate how does ascan() do it, and how you would do it via a do while?
>>>>
>Terry,
>
>Here's an example. I'm doing this off the top of my head, so it hasn't been debugged. Nevertheless, it should be close enough. If there are questions (or mistakes) please let me know. This function will return either the offset into a single dimension array, or the next greatest value. Naturally, the array is passed by referene
FUNCTION BArraySearch
>
>LPARAMETERS tarray, tsearchfor, tlsoftsearch
>
>LOCAL lnfirst, lnlast, lnmid, llfound, lnresult
>lnfirst = 1
>lnlast = ALEN(tarray, 1)
>llfound = .F.
>lnresult = 0
>DO WHILE NOT llfound AND lnfirst < lnlast
>  lnmid = INT(lnfirst + lnlast)
>  llfound = (tsearchfor = tarray[lnmid])
>  IF NOT llfound THEN
>    IF tsearchfor > tarray[lnmid] THEN
>      lnfirst = lnmid + 1
>    ELSE
>      lnlast = lnmid - 1
>    ENDIF
>  ENDIF
>ENDDO
>IF llfound THEN
>  lnresult = lnmid
>ELSE
>  IF llsoftsearch THEN
>    lnresult = lnlast
>  ENDIF
>ENDIF
>RETURN lnresult
The beauty of this is that it can be implemented, not only with a array, but an ordered list or cursor.
Précédent
Suivant
Répondre
Fil
Voir

Click here to load this message in the networking platform