Common PHP algorithm questions and common PHP algorithm questions
1. PHP implements Binary Search
# Binary Search
Function binarySearch (Array $ arr, $ target ){
$ Low = 0;
$ High = count ($ arr)-1;
While ($ low <= $ high ){
$ Mid = floor ($ low + $ high)/2 );
# Finding Elements
If ($ arr [$ mid] ==$ target) return $ mid;
# The element in is larger than the target. Search for the left part.
If ($ arr [$ mid]> $ target) $ high = $ mid-1;
# The key element is smaller than the target. Search for the right part.
If ($ arr [$ mid] <$ target) $ low = $ mid + 1;
}
# Search failed
Return false;
}
$ Arr = array (1, 3, 5, 7, 9, 11 );
$ Tags = binarySearch ($ arr, 1 );
Var_dump ($ dumps );
2. PHP sequential search
Function search ($ array, $ k)
{
$ N = count ($ array );
$ Array [$ n] = $ k;
For ($ I = 0; $ I <$ n; $ I ++)
{
If ($ array [$ I] = $ k)
{
Return $ I;
Break;
}
}
Return-1;
}
$ Array = array (5, 6, 3, 7, 11, 61 );
Echo search ($ array, 11 );