w3resource

JavaScript: Search JavaScript arrays with a binary search

JavaScript Function: Exercise-18 with Solution

Binary Search in Array

Write a function for searching JavaScript arrays with binary searches.

Note : A binary search searches by splitting an array into smaller and smaller chunks until it finds the desired value.

Visual Presentation:

JavaScript:  Search JavaScript arrays with a binary search

Sample Solution-1:

JavaScript Code:

// Define a function named array_binary Search that performs binary search on a sorted array
function array_binarySearch(narray, delement) {
   // Calculate the middle position of the array
   var mposition = Math.floor(narray.length / 2);

   // Check if the middle element is equal to the desired element
   if (narray[mposition] === delement){
      return mposition;
   }
   // Check if the array has only one element and it is not equal to the desired element
   else if (narray.length === 1) 
   {
      // If true, return null as the element is not found
      return null;
   }
   // Check if the middle element is less than the desired element
   else if (narray[mposition] < delement) {
      // Create a new array containing elements to the right of the middle position
      var arr = narray.slice(mposition + 1);
      
      // Recursively call array_binarySearch on the new array
      var res = array_binarySearch(arr, delement);
      
      // Check if the result is null
      if (res === null)
      {
         // If true, return null
         return null;
      }
      else {
         // If false, return the adjusted index by adding mposition + 1 to the result
         return mposition + 1 + res;
      }
   }
   // If the middle element is greater than or equal to the desired element
   else {
      // Create a new array containing elements to the left of the middle position
      var arr1 = narray.slice(0, mposition);
      
      // Recursively call array_binarySearch on the new array
      return array_binarySearch(arr1, delement);
   }
}

// Create an example sorted array
var myArray = [1, 2, 3, 5, 6, 7, 10, 11, 14, 15, 17, 19, 20, 22, 23];

// Log the result of calling array_binarySearch with the input array and desired element to the console
console.log(array_binarySearch(myArray, 6)); 
 

Output:

4

Flowchart:

Flowchart: JavaScript function: Search JavaScript arrays with a binary search

Live Demo:

See the Pen JavaScript - Search JavaScript arrays with a binary search-function-ex- 18 by w3resource (@w3resource) on CodePen.


Sample Solution-2:

JavaScript Code:

// Binary search function for sorted arrays
function binarySearch(arr, target) {
    let low = 0;
    let high = arr.length - 1;

    while (low <= high) {
        // Calculate the middle index
        const mid = Math.floor((low + high) / 2);

        // Check if the middle element is the target
        if (arr[mid] === target) {
            return mid; // Element found, return its index
        } else if (arr[mid] < target) {
            low = mid + 1; // If target is greater, search the right half
        } else {
            high = mid - 1; // If target is smaller, search the left half
        }
    }

    return -1; // Element not found
}

// Example usage:
const sortedArray = [1, 2, 3, 5, 6, 7, 10, 11, 14, 15, 17, 19, 20, 22, 23];
const targetElement = 6;
const resultIndex = binarySearch(sortedArray, targetElement);

// Log the result to the console
console.log(resultIndex);
 

Output:

4

Flowchart:

Flowchart: JavaScript function: Search JavaScript arrays with a binary search

Improve this sample solution and post your code through Disqus.

Previous: Write a JavaScript function to get the number of occurrences of each letter in specified string.
Next: Write a JavaScript function that returns array elements larger than a number.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/javascript-exercises/javascript-function-exercise-18.php