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.
Reply to discussion (solution)
In the future, how many algorithms will be involved in the actual development process?
If ($ Arr [$ MiddleIndex] <$ FindVal ){
Search ($ Arr, $ FindVal, ++ $ MiddleIndex, $ RightIndex );
Is the returned value of ++ $ MiddleIndex replaced with $ LeftIndex?
Equal to the returned function Search ($ Arr, $ FindVal, $ LeftIndex, $ RightIndex) here the values are $ Arr $ FindVal or 6 $ LeftIndex, which is equal to the previous $ MiddleIndex, which is equal to 4? Is that true?
You add
Echo "FindVal: $ FindVal LeftIndex: $ LeftIndex RightIndex: $ RightIndex \ n ";
Can't you see it clearly?
Teach you how to draw time sequence diagrams and analyze more by yourself
Thank you very much for calling Search ($ Arr, $ FindVal, ++ $ MiddleIndex, $ RightIndex) for the second time. can I change the variable location when I call Search? For example, write it like this? Search ($ Arr, $ FindVal, $ RightIndex, ++ $ MiddleIndex );
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 | $ a in the nth function environment | $ 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.
Teach you how to draw time sequence diagrams and analyze more by yourself
Hello, I have read your timing diagram. If the array to be searched for is $ arr = array (, 9), I found that I want to set up several layers of functions. Whether I understand the problem or whether it is true. please consult. Thank you.