1. bubble sorting an array
2. simple query
3. binary query
Code: Select all
#Include "crt.bi"
Dim As String sFruits(...) = { _
"banana","apple","tomato","orange", _
"lime","pineapple","grape","melon", _
"onion","sallery","avocado","cucumber", _
"strawberry","carret","pear","watermelon" }
#Define AttemptPrint Print
'#Define AttemptPrint rem
Sub ShowArray( Array() As String )
For N As Integer = 0 To UBound(Array)
Print Array(N);" ";
Next
Print
End Sub
Sub SortArray( Array() As String )
'Bubble
Do
Dim As Integer iSorted = 0
For N As Integer = 0 To UBound(Array)-1
If Array(N) > Array(N+1) Then
Swap Array(N),Array(N+1): iSorted=1
EndIf
Next
If iSorted = 0 Then Exit Do
Loop
End Sub
Function SimpleQuery( Array() As String , sQuery As String ) As Integer
Var sQueryL = LCase(sQuery)
For N As Integer = 0 To UBound(Array)
If Array(N) = sQueryL Then
AttemptPrint "Attempts: " & N+1,
Return N
EndIf
Next
AttemptPrint "Attempts: " & UBound(Array)+1,
Return -1
End Function
Function BinaryQuery( Array() As String , sQuery As String ) As Integer
Dim As Integer iFirst=0 , iLast=UBound(Array)
Var sQueryL = LCase(sQuery)
Dim As Integer iAttempts
While iLast>=iFirst
iAttempts += 1
Dim As Integer iMid = (iFirst+iLast+1)\2 'cint((iFirst+iLast)/2)
Dim As Integer iResult = strcmp( sQueryL , Array(iMid) )
If iResult = 0 Then
AttemptPrint "Attempts: " & iAttempts,
Return iMid
EndIf
If iResult > 0 Then iFirst = iMid+1 : Continue While
iLast = iMid-1
Wend
AttemptPrint "Attempts: " & iAttempts,
Return -1
End Function
SortArray(sFruits())
ShowArray(sFruits())
Print " ----- SimpleQuery() ----- "
Print "carret",SimpleQuery(sFruits(),"carret")
Print "watermelon",SimpleQuery(sFruits(),"watermelon")
Print "brick",SimpleQuery(sFruits(),"brick")
Print
Print " ----- BinaryQuery() ----- "
Print "carret",BinaryQuery(sFruits(),"carret")
Print "watermelon",BinaryQuery(sFruits(),"watermelon")
Print "brick",BinaryQuery(sFruits(),"brick")
Sleep
I hope this is not considered spam. if so please tell me and I'll stop or erase the post / thread.
thank you.
ron77
okay I removed the link as this was inappropriate