Reputation: 11
I'm trying to implement a binary search in javascript and I'm completely new at JS. I'm mostly used to the C++ syntax, so it's been a little difficult for me to break any habits that I have.
When I include this script in an html doc, it fails to exit the script if the array size is less than 1 and doesn't trigger the array order alert if I enter an unordered array. In addition, the program never seems to finish the while loop, so I don't know if there are any other problems.
Any help would be appreciated!
var size = parseInt(prompt("Enter the size of the array:"));
if(size < 1) {
alert("ERROR: you entered an incorrect value for the array size!");
return;
}
var arr = [size];
var input = parseInt(prompt("Enter the numbers in the array in increasing order,"
+ " separated by a space, and press enter:"));
arr = input.split(" ");
var checkOrder = function(array) {
for(var i = 0; i < size-1; i++) {
if(array[i] > array[i+1]) {
return false;
}
}
return true;
}
if(!checkOrder(arr)) {
alert("The values entered for the array are not in increasing order!");
}
var search = parseInt(prompt("Enter a number to search for in the array: "));
var lp = 0; //left endpoint
var rp = size; //right endpoint
var mid = 0;
var counter = 0;
var found = false;
while(lp <= rp) {
mid = Math.floor((lp + rp)/2);
if(arr[mid] == search) {
alert("Found value " + search + " at index " + mid);
counter++;
found = true;
break;
} else if(arr[mid] > search) {
rp = mid + 1;
counter++;
} else {
lp = mid;
counter++;
}
}
if(!found) {
alert("The value " + search + "was not found in the array");
alert("I wasted " + counter + " checks looking for a value that's not in the array!");
return;
}
Upvotes: 1
Views: 115
Reputation: 3171
Your input method is not right.
Putting array initialization issue aside, the line
var input = parseInt(prompt(".."))
gonna give you one single number.
You can actually skip prompting for array size
var input = prompt('Space separated numbers:')
var array = input.split(' ')
if (array.length == 0) {
alert('._.'); return
}
for (var i = 0; i < array.length; i++)
array[i] = parseInt(array[i])
Upvotes: 0
Reputation: 993423
var arr = [size];
The above code probably isn't doing what you want it to. This creates an array with one element, whose value is the value of size
. You can create an array with a specific initial size by doing this:
var arr = new Array(size);
Upvotes: 3