1

Q display 0 and not the value of c, what is wrong with these code? Am i wrong in the return statement?

main js file

var q=0;
search(a,21,q);
document.getElementById("demo1").innerHTML = q;

another js file

function search(array, target, c) {
  left = 0;
  right = array.length - 1;

  while (left <= right) {
    mid = (left + right) / 2;
    if (array[Math.trunc(mid)] == target) {
      c = Math.trunc(mid);
      console.log(c);

      return array, target, c;

    } else if (target < array[mid]) {
      right = Math.trunc(mid) - 1;
    } else {
      left = Math.trunc(mid) + 1;
    }
  }
}
Mike 'Pomax' Kamermans
  • 49,297
  • 16
  • 112
  • 153
  • 1
    Does this answer your question? [Binary Search in Javascript](https://stackoverflow.com/questions/22697936/binary-search-in-javascript) – Slava Knyazev Jul 23 '22 at 03:52
  • 4
    by the way, `return array,target,c;` will return `c` - is that what you wanted? – Jaromanda X Jul 23 '22 at 03:53
  • Also on a JS note, use `===` unless you're absolutely certain you need type coercion, and use `element.textContent = ...` instead of `element.innerHTML = ...` unless you're absolutely certain you need to convert actual HTML code into DOM content. (in this case, you're just setting a text value). – Mike 'Pomax' Kamermans Jul 23 '22 at 04:02
  • Whatever you do to `c` won't affect `q`. It's comparable to how if you do `c=q; c=something_else;` the `q` won't be affected by the `something_else` – qrsngky Jul 23 '22 at 04:16
  • Another problem: you're simply not using the return value, unless you have something to hold the result like `let something_to_hold_it = search(a,21,q);` – qrsngky Jul 23 '22 at 04:19
  • Please [always declare your variables](https://stackoverflow.com/q/1470488/1048572)! – Bergi Jul 23 '22 at 04:32
  • `q` is being passed by value to search function which does not allow to change the original `q`. In Javascript objects and arrays are passed by reference. So instead of assigning `q` to `0` at the beginnig, consider assigning it to some `obj.q`. Then pass that `obj` to the function and change `obj.q`. – Maf Jul 23 '22 at 07:42

1 Answers1

1

Number in JS is a primitive data type and those types are passed by value, so it will copy the value of q into a new variable named c and if you change c, q will not change.

you can return array[Math.trunc(mid)] and do something like this: document.getElementById("demo1").innerHTML = search(a,21);

m.marian
  • 146
  • 1
  • 6