What is causing the browser to freeze in this binary search implementation?

Recently, I attempted to implement binary search in my Chrome console. However, upon running the code, it caused the entire browser to freeze and I had to forcefully close the tabs:

var array = [1, 3, 5, 8];
var performBinarySearch = function (array, target) {

    var lowerBound = 0;
    var upperBound = array.length - 1;
    var middle = Math.floor((upperBound + lowerBound) / 2);

    while (lowerBound <= upperBound) {

        if (target === array[middle]) {
            return middle;
        } else if (target > array[middle]) {
            lowerBound = middle + 1;
        } else {
            upperBound = middle - 1;
        }

    }
    return -1;
};

console.log(performBinarySearch(array, 3));

Answer №1

There seems to be an issue with the following line

var mid = (high + low) / 2;

Due to the fact that mid is a floating point value, accessing arr[mid] will always result in undefined. You can verify this by trying

var arr = [1, 3, 5, 8];
console.log(arr[1.5]);
// undefined

Possible Solution

  1. To resolve this issue, you can convert the calculated value to an integer, like so

    var mid = parseInt((high + low) / 2, 10);
    
  2. As pointed out in the comments by Rick, the calculation of mid should take place within the while loop. Therefore, the while loop should be adjusted accordingly

    while (low <= high) {
        mid = parseInt((high + low) / 2, 10);
        if (search === arr[mid]) {
            return mid;
        } else if (search > arr[mid]) {
            low = mid + 1;
        } else {
            high = mid - 1;
        }
    }
    

Answer №2

The value of mid in your code is constantly set to 1.5, as it's calculated outside the loop.

To improve this, you should update the calculation of mid inside the loop by determining it as the rounded average between high and low:

var numbers = [2, 6, 10, 14];
var binarySearch = function(numbers, target) {

  var low = 0;
  var high = numbers.length - 1;
  var mid;

  while (low <= high) {
    mid = Math.round((high + low) / 2);
    if (target === numbers[mid]) {
      return mid;
    } else if (target > numbers[mid]) {
      low = mid + 1;
    } else {
      high = mid - 1;
    }
  }

  return -1;
};

console.log(binarySearch(numbers, 6)); //1
console.log(binarySearch(numbers, 14)); //3
console.log(binarySearch(numbers, 17)); //-1

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

Limiting the rate at which a function can be executed in NodeJS

I am facing an issue where I need to create an interval of five seconds during which a function can be executed. The reason for this is because I am monitoring an Arduino serial port, which sends multiple signals when a button is pressed. However, in my no ...

Creating a distinctive vue form component from scratch

I have a requirement to develop a Vue component that enables users to create or edit a mailing address. The existing component structure is as follows: <template> <v-container> <v-form ref="form" lazy-validation> <v-text-field ...

extract keys and values from an array of objects

I would like assistance with removing any objects where the inspectionScheduleQuestionId is null using JS. How can we achieve this? Thank you. #data const data = [ { "id": 0, "inspectionScheduleQuestionId": 1, ...

Retrieving date from timestamp in a node.js environment

Can someone help me figure out how to display my timestamp as the date in the front end? I've tried multiple methods without success. Here is the code snippet: formulaire.addEventListener('submit', posteValidation); /** * Function to add a ...

What's the trick to efficiently managing multiple checkboxes in an array state?

I have a lengthy collection of checkboxes that is not well optimized. I am trying to obtain the checked ones and store them in an array state. However, I am uncertain about how to handle this situation and I would appreciate some assistance. It should also ...

Ways to retrieve a specific element from an ArrayList

Having trouble with selecting from an array list? I'm working on arranging 10 JButtons in a circle and it's going well, but now I want to set individual actionListeners for each button. However, all the buttons seem to inherit the same actions. H ...

Transmit information from an HTML input field (not a form) to a Python CGI script through AJAX

I am currently facing a challenge where I need to send data programmatically without using form fields directly to a python CGI script. The issue lies in not knowing how to extract this data in Python. Normally, with a form, I could use "form = cgi.FieldSt ...

Guide on removing the parent JSON array while retaining the child JSON array

I have been searching for a solution to remove specific JSON array elements, but I have not found one yet. Here is the JSON data I am working with: [ { "KODE": [ { "name": "kode", "value": [ ...

Streamline JSON arrays into separate variables based on their respective categories

Received a JSON output from a PHP file with the following structure; [{"device_id":"9700001","sensor_value":"31.5","update_time":"2017-04-28 18:49:06"}, {"device_id":"9700002","sensor_value":"31.5","update_time":"2017-04-28 18:47:05"}, {"device_id":"97000 ...

Utilizing a SQL LIKE operator within a SELECT statement with Twitter/typeahead.js

Here is the code that I am working with: $places = query("SELECT * FROM places WHERE postal_code = ? or place_name = ? or admin_code1 = ? or admin_name2 = ? or admin_name1 = ?", $_GET["geo"],$_GET["geo"],$_GET["geo"],$_GET["geo"],$_GET["geo"]); When I st ...

Struggling to adjust the carousel selector to display images in the center, not off to the left

Encountering an issue with adjusting the carousel selector to showcase images in the center instead of on the left. The slides are functioning correctly, but the showcase item is not aligning properly. Here is a preview, thank you. <script src="htt ...

Where should you position the $watch function in Angular?

Suppose I have a promise object that my page uses to retrieve data, like so: promise.then(function (data) { $scope.myData = data; }); In addition to this, I have watches on objects located elsewhere on the page. When it comes to watching data provide ...

How to modify a variable within the "beforeSend: function()" using Ajax and jQuery

I am facing an issue with my ajax contact form. The beforeSend function is supposed to validate the inputs and pass the parameters to a PHP file for sending emails. However, I always receive false instead of true even when the inputs are valid. I suspect ...

Using Vue: Save user information in the Vuex store prior to registration

Hello fellow members of the Stackoverflow Community, I am currently working on a Vue.js application that involves user registration. The registration process is divided into three components: Register 1 (email, password), Register 2 (personal information) ...

What is the product of the diagonals in a 4x4 two-dimensional array?

I need help calculating the product of all diagonal numbers in a 4x4 array. I can extract and display the numbers, but unsure how to multiply them together to find the total. How can I modify the code to compute the product of these 8 numbers? #include ...

Multiply elements in an array by using a recursive for loop algorithm

Currently, I am in the process of developing a program that involves multiplying elements in a 2D array with elements in subsequent rows. To accomplish this, I have implemented a recursive method that initially traverses each row of the 2D array, identif ...

How can you use Require.context in Webpack to import all .js files from a directory except those ending in `_test.js`?

My objective was to develop a script that accomplishes the following tasks: Import all JS files from a directory excluding those ending in _test.js Set up a module.exports containing an array of module names extracted from those imported files. Initiall ...

Manipulating SQL database tables using PHP

After struggling for about 5 hours, I'm still unable to make this code work. Despite my best efforts, the unique nature of my codes seems to be a challenge. I am attempting to update entries in a specific table within my SQL database named userdb. The ...

Larger figure on the left side

When provided with an array of numbers, the task is to print the first number on the left side that is greater than the current number for each number in the array. To better illustrate this: Input -> 5,3,2,4,8,6 Output-> -1, 5, ...

differences in opinion between JavaScript code and browser add-ons/extensions

As the owner and developer of an e-commerce website, I find that potential customers often contact us regarding ordering issues. Upon investigation, we consistently discover that the problem is caused by JavaScript errors. We frequently check their browse ...