//Forgetful recursive version of binary search
function binary_search(arr, target,low,high){
if(low var 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 There is one element left
if(arr[low]==target)
return low;
else return -1;
}else if(low>high){ //Empty, use arr .length-1 should be considered when calculating the initial high of arr.
return -1;
}
}
var arr=[1,2,3,4, 5,6];
alert(binary_search(arr,3,0,arr.length-1));
Looking at the data structure at night, I wrote a binary search algorithm in js (the code is as above), and then I randomly wrote an array as the test data (as above). According to the idea, it should output the subscript of the search target, but something unexpected happened. I saw the CPU spinning wildly for an instant. After about two seconds, the browser automatically terminated the script. running, and then I felt puzzled for a while.
According to experience, there should be an infinite loop in the process of running the script. I looked at the algorithm during self-study and found no problems (you can just enter the code directly according to the textbook and you will not be wrong) , but the problem remains. So I added an output statement to the first judgment condition, as follows:
//Binary search forgetful recursive version function binary_search(arr,target,low,high){
if(low var 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 low;
else return -1;
}else if(low>high){ //Empty, it should be considered when using arr.length-1 to calculate the initial high of arr
return -1;
}
}
Run it, and a dialog box will pop up with the number 2.5~~ Suddenly, I suddenly have the urge to smash the computer.
Cause of error and summary:
The "/" operator in JavaScript is different from the "/" operator in C. The latter is automatically rounded, while the former will get a decimal if it is not divided by integers (for example 5/2=2.5).
Solution:
(1)var min=parseInt((low high)/2);
(2)var min=Match.floor((low high)/2);