i just came across binary search and it is very interesting.
i made some simple tests and the result is promising.
i saw a thread by erel about this topic but never put my attention on it now seeing an example on youtube made me a little bit curious.
here is a simple code example (b4j). it will work only on a sorted list. i will need to figure out how it can also work with strings or any kid of object maybe convert obj to bytes -> sort list -> search for the byte and return?? i have not made any tries only with INTEGERS and it works fine.
RESULTS:
i made some simple tests and the result is promising.
i saw a thread by erel about this topic but never put my attention on it now seeing an example on youtube made me a little bit curious.
here is a simple code example (b4j). it will work only on a sorted list. i will need to figure out how it can also work with strings or any kid of object maybe convert obj to bytes -> sort list -> search for the byte and return?? i have not made any tries only with INTEGERS and it works fine.
B4X:
#Region Project Attributes
#MainFormWidth: 600
#MainFormHeight: 600
#End Region
Sub Process_Globals
Private fx As JFX
Private MainForm As Form
Private myList As List
Private valueToSearch As Int = 8515600
End Sub
Sub AppStart (Form1 As Form, Args() As String)
MainForm = Form1
'MainForm.RootPane.LoadLayout("Layout1") 'Load the layout file.
MainForm.Show
myList.Initialize
createList
simpleSearch(myList,valueToSearch)
binarysearch(myList,valueToSearch)
End Sub
Sub simpleSearch(l As List, value As Int) As Int
Dim starttime As Long = DateTime.Now
Dim pos As Int = -1
For i = 0 To l.Size-1
If myList.Get(i) = value Then
pos =1
Exit
End If
Next
Log($"Time: ${DateTime.Now-starttime} ms"$)
Return pos
End Sub
Sub binarysearch(l As List, value As Int) As Int
Dim starttime As Long = DateTime.Now
Dim pos As Int = -1
Dim low=0, middle, high=l.Size-1 As Int
Do While low <= high
middle = Floor((low+high)/2)
If myList.Get(middle) = value Then
pos = middle
Exit
Else if myList.Get(middle) > value Then
high = middle -1
Else
low = middle + 1
End If
Loop
Log($"Time: ${DateTime.Now-starttime} ms"$)
Return pos
End Sub
Sub createList
For i = 0 To 10000000
myList.Add(i)
Next
End Sub
'Return true to allow the default exceptions handler to handle the uncaught exception.
Sub Application_Error (Error As Exception, StackTrace As String) As Boolean
Return True
End Sub
RESULTS: