Main Menu

Linear Searching

Started by kevin, January 14, 2006, 05:54:52 PM

Previous topic - Next topic

kevin





PlayBASIC Code: [Select]
; *=-------------------------------------------------------------------------=*
;
; This example shows how you could perform a simple linear upon an integer
; array.
;
; What is it ?
; ================
;
; Conceptually, a Linear search is the simplest form of searching possible:
; It involves simply running all the way through (sequentially) our data
; structure (an array in this case) and comparing the each value or string
; to our search value. If a match a found we exit and return this elements
; position. But if no match was found we return a -1.

; Note: While Thankfully in PlayBasic we can we can use the FindArrayCell()
; function to do the grunt work for us. Linear searching is a brute
; force operation. While it'll fast on small sets of data, it can be
; a real mouth full on larger sets, in particular if you need to perform
; many searches.
;
; *=-------------------------------------------------------------------------=*


Size=20

; Fill an array with values from 0 to size
Dim RandomValues(size)
For lp=0 to size
RandomValues(lp)=lp
next

; Now Shuffle these values so there in a random order
For lp=0 to size
Item1 =rnd(size)
Item2 =rnd(size)
a=RandomValues(item1)
b=RandomValues(item2)
RandomValues(item1)=b
RandomValues(item2)=a
next


; Show the Array contents
Print "RandomValues() Array Contents:"
print ""
For lp=0 to size
print digits$(lp,2)+" "+str$(Randomvalues(lp))
next



setcursor 0,0
cursormargin 300
Print "Results of Linear searching the RandomValues() array"
print ""

for lp=0 to 10
FindValue=rnd(20)
Print " Searching For Value:"+str$(FindValue)
Foundat=SearchArray(RandomValues(),FindValue)
if FoundAt=-1
print "Value not found"
else
print "Found at array index:"+Str$(foundat)
endif
print ""
next

Sync
waitkey



; =-----------------------------------------------------------------=*
; Search an Integer Array looking for an Integer Value
; =-----------------------------------------------------------------=*

Function SearchArray(array(),FindThisValue)
; Get the current size of this array
Size=GetArrayElements(Array(),1)
; Call Find array cell to locate this element.
FoundAt=findarraycell(array(), 0,1,size,FindthisValue)
EndFunction FoundAt