0

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

sirisakc
  • 892
  • 2
  • 15
  • 30
  • 2
    The value you enter is a string, but the array contains numbers. So, the comparison fails. You should change the equality operator to the loose equality "==" than the strict one. – Mario Vernari Apr 22 '22 at 04:32

2 Answers2

3

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 ==.

Diego Fidalgo
  • 480
  • 3
  • 8
  • 1
    Perfect Solution !!! (1) e.target.value with "string" type (2) onChange with fix solution (Number) (3) operator === and == – sirisakc Apr 22 '22 at 14:15
0

Thank you very much @Mario Vernari

I update the below line to change from string to number, it works properly. (Insert '+' to insertValue)

From

<h3>Search {insertValue}, Result in location: {binarySearch(exarr,insertValue)}</h3>

To

<h3>Search {insertValue}, Result in location: {binarySearch(exarr, +insertValue)}</h3>

enter image description here

sirisakc
  • 892
  • 2
  • 15
  • 30