Has the binary search operation not been executed?

My attempt to implement the binary search algorithm in my code example is not producing the expected result. I'm unsure of the cause. Can someone please explain it to me?

var array = [1, 4, 6, 8, 9, 12, 15, 17, 19, 34, 55, 78, 80];

function binarySearch (array, numberToSearch) {
var firstIndex = 0;
var lastIndex = array.length - 1;
var currentIndex;
var currentElement;

currentIndex = (lastIndex + firstIndex) / 2 | 2;
currentElement = array[currentIndex];

while (firstIndex <= lastIndex) {
    if (numberToSearch === currentElement) {
        // found
        console.log(currentIndex);
        return currentIndex;
    } else if (numberToSearch < currentElement) {
        lastIndex = currentIndex - 1;
        currentIndex = (lastIndex + firstIndex) / 2 | 2;
        currentElement = array[currentIndex];
    } else if (numberToSearch > currentElement) {
        firstIndex = currentIndex + 1;
        currentIndex = (lastIndex + firstIndex) / 2 | 2;
        currentElement = array[currentIndex];
    }
}
 return -1;
}
binarySearch(array, 12);

When running the function with the value of 12, I should be getting a result of 5, but nothing is happening.

Answer №1

What issue is present in the code:

  1. The correct syntax should be

    var currentIndex = (lastIndex + firstIndex) / 2 | 0;
    (instead of | 2);

  2. currentIndex and currentElement need to be recalculated during each iteration within the loop.

Therefore, here is the revised version of your code:

var array = [1, 4, 6, 8, 9, 12, 15, 17, 19, 34, 55, 78, 80];

function binarySearch (array, numberToSearch) {
var firstIndex = 0;
var lastIndex = array.length - 1;

while (firstIndex <= lastIndex) {
    var currentIndex = (lastIndex + firstIndex) / 2 | 0;
    var currentElement = array[currentIndex];
    if (numberToSearch === currentElement) {
        return currentIndex;
    } else if (numberToSearch < currentElement) {
        lastIndex = currentIndex - 1;
    } else if (numberToSearch > currentElement) {
        firstIndex = currentIndex + 1;
    }
}
 return -1;
}

console.log(binarySearch(array, 99)); // -1
console.log(binarySearch(array, 12)); // 5

By the way, using

var currentIndex = (lastIndex + firstIndex) / 2 | 0;
may be unfamiliar. A more common approach is
var currentIndex = Math.floor((lastIndex + firstIndex) / 2);

Answer №2

Let's discuss the purpose of using the bitwise operand OR in this situation:

currentIndex = (lastIndex + firstIndex) / 2 | 2;

It seems that a correction is needed. The expression should simply be:

currentIndex = (lastIndex + firstIndex) / 2;

There appears to be an error in updating the search space. When

numberToSearch < currentElement
, indicating that the middle element (element at index currentIndex) is greater than the number being searched, the correct adjustment for the boundaries would be:

lastIndex = currentIndex - 1;

Similarly, when

numberToSearch > currentElement
, showing that the middle element (element at index currentIndex) is less than the number being searched, the proper update for the boundaries should be:

firstIndex = currentIndex + 1;

The revised and accurate code snippet is as follows:

var array = [1, 4, 6, 8, 9, 12, 15, 17, 19, 34, 55, 78, 80];

function binarySearch(array, numberToSearch) {
    var firstIndex = 0;
    var lastIndex = array.length - 1;
    var currentIndex;
    var currentElement;

    currentIndex = (lastIndex + firstIndex) / 2;
    currentElement = array[currentIndex];

    while (firstIndex <= lastIndex) {
        if (numberToSearch === currentElement) {
            // Element found
            console.log(currentIndex);
            return currentIndex;
        } else if (numberToSearch < currentElement) {
            lastIndex = currentIndex - 1;
            currentIndex = (lastIndex + firstIndex) / 2;
            currentElement = array[currentIndex];
        } else if (numberToSearch > currentElement) {
            firstIndex = currentIndex + 1;
            currentIndex = (lastIndex + firstIndex) / 2;
            currentElement = array[currentIndex];
        }
    }

    return -1;
}
binarySearch(array, 12);

Answer №3

I have made the necessary updates to your answer. You were almost there! It appeared that you mixed up the iterative binary search with the recursive solution.

Check out this CodePen Demo

var array = [1, 4, 6, 8, 9, 12, 15, 17, 19, 34, 55, 78, 80];

function binarySearch (array, numberToSearch) {
  var firstIndex = 0;
  var lastIndex = array.length - 1;
  var currentIndex;
  var currentElement;

  while (firstIndex <= lastIndex) {
    currentIndex = (lastIndex + firstIndex) / 2 | 0; //should default to zero, not Two! 
    currentElement = array[currentIndex];//These should both update every iteration so it does not infinitely loop!
    if (numberToSearch === currentElement) {
      // found
      console.log(currentIndex);
      return currentIndex;
    }else if (numberToSearch < currentElement) {
      lastIndex = currentIndex - 1; //If current is too big, move right pointer to the left
    }else if (numberToSearch > currentElement) {
      firstIndex = currentIndex + 1;//If current is too small, move left pointer to the right
    }
  }
  return -1;//When condition of while it broken and no solution has been found, return -1 to indicate it is not in the array
}
binarySearch(array, 12) //5

This approach is further optimized by not using Math.floor() as number | 0 can be faster at times.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

React Native Header Icon Not Showing on the Left Side

I'm brand new to react and currently working on a project where navigation is done through a hamburger menu. I haven't encountered any errors in my code, but for some reason, the hamburger menu icon isn't displaying as expected. Interestingl ...

"Why does adding a new span create space between it and the previous ones, and what can be done to prevent this from

Essentially, it creates the equation "a + b = c". However, I need to create "a + b = c" instead. HTML: <div class="container"> <span id="b__value">+b</span> <span id="c__value">=c</span> &l ...

Next.JS reported that it "Executed a greater number of hooks compared to the previous render"

Currently, I am utilizing useSWR to fetch data from my express and mongo-db backend. The retrieval of data from the database is successful without any issues. Below is the code snippet that allowed me to do this: //SWR method for hydration const fetcher = ...

Struggling to display my array data retrieved from the database on my Angular 5 page

I hope everyone is doing well. I am currently facing a problem with retrieving data from Firebase. I have an array within an array and I want to display it in my view, but I am encountering difficulties. Let me share my code and explain what I am trying to ...

Offering various language options on a website determined by the URL

I've been contemplating how to add multi-language support to my personal website, which I developed using ExpressJS and NodeJS with EJS as the template engine. Currently, the website is only available in English, but I want to add a German version as ...

Access the value of a variable passed from the view to the controller

Is there a way to retrieve a dynamically generated value from the view to the controller in AngularJS? <ng-option ng-repeat="w in details track by $index"> <div class="program-grid-row table-row" > <div> <a class= ...

The scroll feature in JavaScript is malfunctioning

After countless hours of troubleshooting, I still can't figure out why the code snippet below is not working properly on my website at : <script> $(window).scroll(function () { if ($(window).scrollTop() > 400) { ...

"Struggling with solving an error in METEOR REACT SEARCH and DISPLAY upon user input onChange? Let

Here is the input code snippet: Title: <input type="text" ref="searchTitle" onChange={this.searchTitle}/> This function handles the onChange event: searchTitle(event) { this.setState({ show_article_editable_list: <Article_Editab ...

reading blocks of 2-byte integers

Currently, I am importing a file containing 2-byte-long integers into an array FILE *f = fopen("file.bin", "rb"); int *arr; int len = 2; The following method is functional: // Approach 1 for (int i = 0; i < numberOfElements; i++) fread(arr + i, ...

Make sure to validate onsubmit and submit the form using ajax - it's crucial

Seeking assistance for validating a form and sending it with AJAX. Validation without the use of ''onsubmit="return validateForm(this);"'' is not functioning properly. However, when the form is correct, it still sends the form (page r ...

Tips on arranging jQuery deferred objects in order?

I am facing an issue where I need to delay every Ajax call until the previous function (hashcode.Sign()) has completed. Unfortunately, my current code does not wait for hashcode.Sign() to finish, causing problems as this function creates a new session that ...

AngularFire Google OAuth failing to retrieve the user's email address

I am trying to retrieve the email address from Google OAuth using AngularFire, but the popup is not requesting permission for the email. This code snippet is from the Firebase Google authentication documentation var ref = new Firebase("https://<your-f ...

Unable to remove spaces in string using Jquery, except when they exist between words

My goal is to eliminate all white spaces from a string while keeping the spaces between words intact. I attempted the following method, but it did not yield the desired result. Input String = IF ( @F_28º@FC_89º = " @Very strongº " , 100 , IF ( @F_28 ...

Utilizing Vue.js to pass a slot to a customized Bootstrap-Vue Table component

I am currently in the process of developing a wrapper for the bootstrap-vue Table component. This particular component utilizes slots to specify cell templates, similar to the following example: <b-table :items="itemsProvider" v-bind="options"> ...

Identifying sluggish GPU performance on a mobile device using three.js: A guide for developers

My game runs extremely slow on older mobile devices like the Samsung Galaxy S4 and iPhone 5 when shadows are enabled. However, when shadows are turned off, performance improves significantly. Is there a way to detect a slow GPU in order to disable sh ...

Python: Exploring Multi-Index Looping

Creating a loop in Java or C is very straightforward and simple. for (int i = 0; i <arr.length()-1; i++) { for (int j = i+1; j <arr.length(); j++) { //process } } However, I am having trouble replicating this in Python. For instance: for ...

Encountering issues with running an AngularJS application (version 1.6) in Visual Studio following the activation of script

I am new to working on an angular 1.6 application and still learning the ropes. The project consists of an asp.net web api project that needs to be run before starting the angular project. Everything was running smoothly until I tried to debug a parameter ...

Leveraging JavaScript to trigger onClick() functions for multiple buttons throughout a webpage

        While searching for solutions, I came across several articles with similar topics, but unfortunately, none of the proposed solutions worked. Please forgive me if it was due to my own error. Background I am assisting a client who is transition ...

Utilize jQuery to toggle classes on multiple elements in web development

I've been struggling to streamline this code I created for the website's navigation. As a novice in Javascript and jQuery, I would appreciate any help or advice. Thank you! Since the page doesn't reload, I have implemented the following met ...

Neglecting to pass data to the controller through the onclick function

Using this specific button element in my JavaScript implementation has raised some concerns. <button id="bid" type="button" class="button" onclick="connect()">Save</button> While I have noticed that it displays an alert message when 'ale ...