here is my code:
let array = [1,2,3,4,5,6,7,8,9,10];
function searcher(arr, target){
let start = 0;
let end = arr.length-1;
let mid = 0;
let a = 100;
while(a>0){
a--;
mid = Math.floor(start+end/2);
if(arr[mid] == target){
return mid;
}else{
if(arr[mid] < target){
start = mid+1;
}else{
end = mid-1
}
}
}
return "doesn't exist";
}
console.log(searcher(array, 6));
this code can get indexes of the numbers 1 and 2 and 4 and 5 but not for 3 and 6 and 7 and 8 and 9 and 10, it throws: “doesn’t exist” instead, which means the loop ends before it finds the value even though all those values exist in the array given to the function.
I tried this from a freecodecamp video Treehouse created, it talks about algorithms.
can any body tell me why my code doesn’t work all the time or how to improve it?
thank you sir/mem/miss/he/she/they