lundi 22 juillet 2019

How to use "return" in if statements javascript

I need help on executing this code cleanly. I am trying to implement an elementary way in which binary search is done.

I noticed that the first "if" block of code does not "return" the value "middle" except I have console.log some code earlier in that block. I need help on using "if" or "if else"; Or haply a cleaner way this program could be written.

Thank you in advance.

let arr = [1,2,3,4,5,6,7,8,9,10];
let length = arr.length;
let left = 0;
let end = length-1;
let right = end;
let mid = Math.floor(length/2);
let middle = mid;

function binarySearch(arr, val){
  console.log("===================");
  console.log(`right is ${right}`);
  console.log(`middle is ${middle}`);
  console.log(`left is ${left}`);
  console.log(`value of val is ${val}`);
  console.log(arr);
  console.log("===================");
//   function iterator() {
if (arr[middle] === val) {
  console.log("The value has been found");
  return middle;
}
if (arr[middle] < val){
  left = middle;
  middle += Math.floor((right-left)/2);
  right = right;
  binarySearch(arr, val);
}
if (arr[middle] > val){
  right = middle;
  middle -= Math.floor((right-left)/2);
  left = left;
  binarySearch(arr, val);
}
else if (left === middle || middle === right) {
  return -1;
}
//   }
}

binarySearch(arr, 2);

I noticed the second block keeps running (stack overflow). For instance, if binarySearch(arr, 8), it results in a stack overflow.

Aucun commentaire:

Enregistrer un commentaire