Why won't my binary search work for numbers that are double digits?

30 Views Asked by At

My binary search only works for single digits. I am trying to run a very simple React program to visualize a binary search but for now, the basic search will not work. Here are all the important parts for that code.

function binarySearch(arr, val) {
    let start = 0;
    let end = arr.length - 1;
  
    while (start <= end) {
      let mid = Math.floor((start + end) / 2);
  
      if (arr[mid] === val) {
        return mid;
      }
  
      if (val < arr[mid]) {
        end = mid - 1;
      } else {
        start = mid + 1;
      }
    }
    return -1;
  }
 

export const BinarySearch = () => {
    const [outputArea, setOutputArea] = useState('');


    const runSearch = (arr, x) => {
        const searched = binarySearch(arr, x);
        setOutputArea(searched + 1);
    }
    


    return (

        <div>
            Enter List: <input type="text"
                        id="listEntry" />
            Enter Number: <input type="text"
                        id="numberEntry" />

            <button type="button"
            onClick={(e) => runSearch(document.getElementById("listEntry").value.split(","), document.getElementById("numberEntry").value)}
            ></button>

            <textarea name="output"  cols="30" rows="10" value={outputArea}></textarea>



        </div>

    );

I tried looking at different versions of the search but no options available have worked. The length of the array does not matter as long as the target number is a single digit.

function binarySearch(arr, val) {
  let start = 0;
  let end = arr.length - 1;

  while (start <= end) {
    let mid = Math.floor((start + end) / 2);

    if (arr[mid] === val) {
      return mid;
    }

    if (val < arr[mid]) {
      end = mid - 1;
    } else {
      start = mid + 1;
    }
  }
  return -1;
}

const runSearch = (arr, x) => {
  return binarySearch(arr, x);
  setOutputArea(searched + 1);
}
<div>
  Enter List: <input type="text" id="listEntry" /> Enter Number: <input type="text" id="numberEntry" />

  <button type="button" onclick="document.getElementById('output').value = runSearch( document.getElementById('listEntry').value.split(','), document.getElementById('numberEntry').value)">Search</button>

  <textarea id="output" name="output" cols="30" rows="10"></textarea>


</div>

0

There are 0 best solutions below