Binary Lookup forgetful recursive version
Copy Code code as follows:
function Binary_search (Arr,target,low,high) {
if (Lowvar min= (Low+high)/2;
if (Target>arr[min])
Return Binary_search (Arr,target,min+1,high);
Else
Return Binary_search (arr,target,low,min);
}else if (Low==high) {//Only one element left
if (arr[low]==target)
return to Low;
else return-1;
}else if (Low>high) {//NULL to be considered when calculating the initial high of arr with arr.length-1
return-1;
}
}
var arr=[1,2,3,4,5,6];
Alert (Binary_search (arr,3,0,arr.length-1));
Look at the data structure at night, by the way JS wrote a binary lookup algorithm (code as above), and then casually wrote the number of groups as test data (such as above), according to the idea should be the output to find the target of the subscript, but the intention is not to happen, see the CPU crazy turn, about two seconds later, the browser automatically terminated the script's operation, Then I wondered.
According to experience, should be in the script run the process of the dead loop, Self-Study looked at the algorithm, did not find any problems (simply follow the textbook code input is always not wrong), but the problem remains. So I added an output statement to the first judgment condition, as follows:
Copy Code code as follows:
Two-point lookup forgetful recursive version function Binary_search (Arr,target,low,high) {
if (Lowvar min= (Low+high)/2;
if (Target>arr[min])
Return Binary_search (Arr,target,min+1,high);
Else
Return Binary_search (arr,target,low,min);
}else if (Low==high) {//Only one element left
if (arr[low]==target)
return to Low;
else return-1;
}else if (Low>high) {//NULL to be considered when calculating the initial high of arr with arr.length-1
return-1;
}
}
Run, pop-up dialog box, inside the number for 2.5~~ suddenly have a sudden and want to hit the computer impulse.
Reasons for error and summary:
The "/" operator in JavaScript is not the same as the "/" operator in C + +, which is automatically rounded up with decimals (for example, 5/2=2.5) if the former is divided evenly.
Solution:
(1) var min=parseint ((Low+high)/2);
(2) var min=match.floor ((Low+high)/2);