Search code examples
reactjsbinary-search

ReactJS - I implement Binary Search Function, it works only first time


ReactJS - I implement Binary Search Function, it works only first time but after I change the value in the input box, it always return -1 even it has the value in the Array.

Please see the following code:

import React, { useState } from 'react'
import { Container } from 'react-bootstrap'

const binarysearch = () => {
  const [ insertValue, setInsertValue ] = useState(0)
  var exarr = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]
  // Binary Search
  const binarySearch = (arr, val) => {
    let start = 0, end = arr.length - 1

    while (start <= end) {
      let mid = Math.floor((start + end)/2)
      console.log(mid)
      if (arr[mid] === val) {
        return mid
      }

      if (val < arr[mid]) {
        end = mid - 1
      } else {
        start = mid + 1
      }
    }
    return -1
  }
  // End Binary Search

  return (
    <div>
      <br />
      <hr />
      <Container>
        <h1>Binary Search</h1>
        <h4>Array = {JSON.stringify(exarr)}</h4>
        <h4>Search <input type="number" onChange={e => setInsertValue(e.target.value)} /></h4>
        <h3>Search {insertValue}, Result in location: {binarySearch(exarr,insertValue)}</h3>
      </Container>
      <hr />
    </div>
  )
}

export default binarysearch

First Time Load enter image description here After Change Input (Search 10 it should return 10 but -1) enter image description here


Solution

  • The problem is the fact that e.target.value is always a string, even when the input type attribute is set to "number".

    So, when you do arr[mid] === val it will be always false, since this is comparing a number to a string.

    You can see this behaviour here.

    To fix this, do onChange={e => setInsertValue(Number(e.target.value))}.

    Or, alternatively, you can use the non strict equality comparison, which is not really recommended, by replacing the === operator by just ==.