Recursive binary search. hope you can help me find the explanation. & lt ;? Php & nbsp; $ Arr = array (1, 2, 3, 4, 5, 6); Search ($ Arr, 6, 0, count ($ Arr)-1); function & nbsp; search ($ Arr, $ FindVal, $ Lef recursive binary Search. hope you can help me explain it.
$ Arr = array (1, 2, 3, 4, 5, 6 );
Search ($ Arr, 6, 0, count ($ Arr)-1 );
Function Search ($ Arr, $ FindVal, $ LeftIndex, $ RightIndex ){
If ($ FindVal> $ Arr [count ($ Arr)-1]) {
Echo "this value cannot be found ";
} Else if ($ FindVal <$ Arr [0]) {
Echo "this value cannot be found ";
} Else {
$ MiddleIndex = round ($ LeftIndex + $ RightIndex)/2 );
If ($ Arr [$ MiddleIndex] <$ FindVal ){
Search ($ Arr, $ FindVal, ++ $ MiddleIndex, $ RightIndex );
} Else if ($ Arr [$ MiddleIndex]> $ FindVal ){
Search ($ Arr, $ FindVal, $ LeftIndex, -- $ MiddleIndex );
} Else {
Echo "find the subscript $ MiddleIndex ";
}
}
}
?> This is the code of recursive binary search. I want to explain it in detail. Currently, I don't know how to implement this recursive method. a little dizzy. thank you for your help:
------ Solution --------------------
Teach you how to draw time sequence diagrams and analyze more by yourself
------ Solution --------------------
Without sending code based on you, the internal and external variable names of the function are not in any relationship, so the order can be changed at will.
Taking the sequence diagram above for example, you can think that every column is a completely new environment. for example, three columns have variables $ a, but they refer to different things (memory space)
$ A in the global environment
------ Solution --------------------
$ A in the nth function environment
------ Solution --------------------
$ A in the second function environment
Although the names are the same, they are indeed different.
It's like there are three on the first floor, three on the second floor, and three on the third floor, which means three people, not the same person, because they are in different environments.
However, you cannot change the code logic because $ RightIndex in Environment 1 and $ RightIndex in Environment 2 both need the same value.
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.
A Free Trial That Lets You Build Big!
Start building with 50+ products and up to 12 months usage for Elastic Compute Service