increases yielding varied outcomes in binary search results

While working on a simple binary search algorithm, I encountered an issue where using mid-- gave different results compared to mid -= 1 or mid - 1, ultimately causing the function to fail. After researching online and reading various Stack Overflow posts, it appears that the -- and ++ operators can impact the value of mid for each iteration. However, the exact behavior behind these operators seems quite nuanced and difficult to track. Any assistance on this matter would be greatly appreciated.

My understanding is that both mid -= 1 and mid-- are intended to decrease the value of mid by one, effectively assigning the new value of mid as -1.

Correct Implementation

const sourceArray = [1, 5, 7, 10, 15];

const binarySearch = (array, target) => {
  let low = 0;
  let high = array.length - 1;

  while (low < high) {
    let mid = (low + high) / 2;
    if (array[mid] === target) {
      return mid;
    } else if (array[mid] > target) {
      // if array[mid] > target, set high to mid--
      high = mid--;
    } else {
      // if array[mid] < target, set low to mid++
      low = mid++;
    }
  }
  return [];
};

console.log(binarySearch(sourceArray, 7));
console.log(binarySearch(sourceArray, 10));
console.log(binarySearch(sourceArray, 15));
console.log(binarySearch(sourceArray, 20));

// returns
// 2
// 3
// 4
// []

Incorrect Implementation

const sourceArray = [1, 5, 7, 10, 15];

const binarySearch = (array, target) => {
  let low = 0;
  let high = array.length - 1;

  while (low < high) {
    let mid = (low + high) / 2;
    if (array[mid] === target) {
      return mid;
    } else if (array[mid] > target) {
      // if array[mid] > target, set high to mid--
      high = mid -= 1;
    } else {
      // if array[mid] < target, set low to mid++
      low = mid += 1;
    }
  }
  return [];
};

console.log(binarySearch(sourceArray, 7));
console.log(binarySearch(sourceArray, 10));
console.log(binarySearch(sourceArray, 15));
console.log(binarySearch(sourceArray, 20));

// returns
// 2
// []
// []
// []

Answer №1

When using the post-decrement operator (--), the value is returned and then decreased. For instance, if the value of mid is 3, the line:

high = mid--;

Will set high to 3 and reduce mid by 1, resulting in a new value of 2 for mid.

In the case of having two assignments on the same line, like in your second example:

high = mid -= 1;

Consider again a scenario where mid has a value of 3. Multiple assignments within one statement are executed from right to left. First, you subtract 1 from mid, storing the result of 2 back into mid. Then, this updated value of 2 is assigned to high.

Answer №2

Initially, make sure that the while condition reads as low <= high. It is important to consider scenarios where the array has only one element, which would skip the loop entirely.

Next, it is recommended to use Math.floor((low + high) / 2); instead of your current approach. When the variables low and high have different parities, the midpoint value will be a fraction. This could lead to trying to access elements like sourceArray[2.5], resulting in undefined behavior.

Lastly, leverage prefix increment and decrement operators as they return the updated value after modifying i.e. --mid and ++mid

The adjustments I implemented in your code are:

const sourceArray = [1, 5, 7, 10, 15];

const binarySearch = (array, target) => {
  let low = 0;
  let high = array.length - 1;

  while (low <= high) {
    let mid = Math.floor((low + high) / 2);
    if (array[mid] === target) {
      return mid;
    } else if (array[mid] > target) {
      // if array[mid] > target, update high to mid - 1
      high = --mid;
    } else {
      // if array[mid] < target, update low to mid + 1
      low = ++mid;
    }
  }
  return [];
};

console.log(binarySearch(sourceArray, 7));
console.log(binarySearch(sourceArray, 10));
console.log(binarySearch(sourceArray, 15));
console.log(binarySearch(sourceArray, 20));

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

Add information in the JSON structure

I am trying to display some JSON data in a div, but the current code is not working. Can anyone suggest where I should make changes? <div class="risktable"> </div> $.ajax({ contentType:'application/json', data: {"sp ...

Choose a division of an element within an embedded frame

Two different pages on the same website, Home.html and Page2.html. Home.html contains the following code: <html> <iframe id="one" src="page2.html" style="display:none"></iframe> <div id="container"> <h1& ...

Send data to colorbox within the current webpage

Hey everyone, I could really use some assistance here, I am trying to figure out how to pass the Data-id value to a Color Box Popup. Can anyone guide me on what steps I need to take? Alternatively, is there another method to achieve the same outcome? JS ...

Learn the process of merging an array element into another object and keeping track of the total count

Initially, my array contains object elements as shown below: $scope.selectedIngredient = [object1, object2, object3, object1, object2]; Next, I have a new object : $scope.selectedIngredientResults = {}; Now, I want to create a JavaScript function that ...

Setting up GoogleProvider with Next Auth in your Next 13 application: A step-by-step guide

Having some trouble setting up the authentication system for my NextJS 13 Experimental App and src folder. Every time I try to authenticate, I get redirected to http://localhost:3000/api/auth/error with a 404 error. I have configured Google OAuth Credenti ...

react-helmet isn't detecting all the dynamic meta properties

Utilizing React to generate preview images for various platforms like WhatsApp and Facebook has been my current focus. My goal is to have the preview image correspond to a specific product when a distinct URL is provided. Currently, I have managed to disp ...

Is there a way to send a Razor boolean variable to an Angular directive?

Within my cshtml file, I am working with a boolean variable. However, when attempting to pass this variable to my Angular directive, it is being received as "False" rather than "false". Even hardcoding it to be "false" in lowercase does not solve the issue ...

What is the best way to layer three or more canvases on top of each other?

I am trying to overlay three or more canvases correctly, but I am struggling. I have come across similar topics (How to place two canvases on top of one another?), but I can't seem to figure out how to stack all 3 or 4 canvases together. Whenever I ad ...

Executing a React asynchronous function within a UseEffect wrapper

I'm having trouble grasping the concept of how an async function operates. It's puzzling to me that the console.log is throwing an error because the data.rates doesn't exist yet. I was under the impression that since the useEffect function ...

Automatically create index.d.ts type definitions from a TypeScript module with just a few clicks

If I have a TypeScript module named my-function.ts with the following code : export function myFunction (param: number): number { return param } When this module is compiled to JavaScript, it loses its type definitions. Is there a way to automatically ge ...

What is the most effective method for detecting the conclusion of a wheel event in JavaScript?

Is there a way to trigger an event once my wheel event has finished? I came across a solution that uses a scroll event (which is similar) with a setTimeout function here: However, I'm curious if there's a more elegant method to detect when my w ...

What is the best way to retrieve data obtained through a node module and incorporate it into my HTML code within NodeWebkit?

I've been working on developing an app with NodeWebkit and utilizing the node-phantom-simple module for content scraping. While I have successfully scraped content from a website, I'm now wondering how I can access this data on the HTML side with ...

An unusual problem stemming from jQuery/AJAX arises when variables within a function fail to update while a click

I've been struggling with a small issue for the past three days that I just can't seem to resolve. It doesn't seem to be a coding error, but rather a misunderstanding of variables and why the onClick event isn't functioning properly. H ...

Warning: Node 125008 has reached the maximum number of listeners, indicating a potential memory leak in the EventEmitter

(node:125008) MaxListenersExceededWarning: There may be a memory leak with EventEmitter as 11 ready listeners have been added. Try using emitter.setMaxListeners() to raise the limit Can anyone provide guidance on how to increase the listener event count? ...

The complexities surrounding array prop management in React Native can be perplex

Within my codebase, I am working with a parent component called ManySpace and a child component named OtherComponent. The OtherComponent is responsible for rendering two instances of the ManySpace component, each with a different array assigned to the many ...

Applying a consistent Selection Filter across multiple routes using identical data but varying selections

Included in the main screen are Selection Filters, which consist of 3 levels: Country, Cities, and Recreations. These filters need to be consistent across all routes, with "select all" at all levels upon initial load. However, a new route has been introd ...

What's the best way to implement asynchronous state updating in React and Redux?

In my React incremental-style game, I have a setInterval function set up in App.ts: useEffect(() => { const loop = setInterval(() => { if (runStatus) { setTime(time + 1); } }, rate); return () => clearInterval(lo ...

Is the creation and disposal of canvas objects in Chrome costly?

In order to keep my code simple, I prefer to create a temporary canvas for a specific task and discard it once I am finished, rather than attempting to reuse or readjust one single canvas repeatedly. Is there a definitive source or opinion that recommends ...

Ways to dynamically update CSS properties (such as changing the color scheme throughout the entire application)

I have a question... If you're interested in conditional styling, the best approach is to utilize either ng-class or ng-style. However... For instance, let's say I'm an admin and I would like to customize the color of my application using ...

Creating customized npm package.json scripts for each individual console command

When running npm install <module> --save, the module is added to the package.json, which can be quite convenient. In the package.json, there is a section dedicated to scripts. It would be helpful to have a command that automatically adds scripts her ...