Binary Search Algorithm, Binary Search Algorithm
Prerequisites for the binary search algorithm:
1. index array;
2. It is for an array that has been prepared.
Code Demonstration:
// Function: searches for data from the position $ begin the array $ arr to the position $ end $ sfunction binary_search ($ arr, $ s, $ begin, $ end) {$ mid = floor ($ begin + $ end)/2); // locate the middle position $ mid_value = $ arr [$ mid]; // obtain the value of the intermediate item if ($ mid_value = $ s) {return true;} else if ($ mid_value> $ s) {if ($ begin> $ mid-1) // if the start position is greater than the end position, {return false;} cannot be found ;} // The intermediate item is larger than the $ s to be searched. Find it on the left: $ re = binary_search ($ arr, $ s, $ begin, $ mid-1 );} else {if ($ mid + 1> $ end) // if the start position is greater than the end position, {return false;} cannot be found ;} // The intermediate item is smaller than the $ s to be searched. Find it on the right. $ re = binary_search ($ arr, $ s, $ mid + 1, $ end );} return $ re ;}
Test code:
<? Php $ a = array (,); $ search = 35; // The number to be searched $ len = count ($ a); // quantity, natural, maximum subscript is len-1 // use binary_search () function from $ a to len-1 location find $ search $ v1 = binary_search ($ a, $ search, 0, $ len-1); echo "Result :"; var_dump ($ v1 );
Test results:
· Result: bool (false)
A description of the efficiency (performance) of the Binary Search Algorithm:
1000 pieces of data, which can be found about 10 times;
100 pieces of data are found about 20 times;
1 billion pieces of data, which can be found about 30 times;
4 billion pieces of data, which can be found about 32 times.