

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Searching for a query using binary search in JavaScript
We are required to write a JavaScript function that takes in a sorted array of literals as the first argument and a query literal as second. Then our function should make use of the Binary Search algorithm to find whether the query exists in the array or not.
If it exists, we return its index in the array, otherwise we return -1.
Example
The code for this will be −
const arr = [1, 2, 3, 5, 6, 7, 10, 11, 14, 15, 17, 19, 20, 22, 23]; const binarySearch = (arr, query) => { let index = Math.floor(arr.length / 2); if (arr[index] === query){ return index; }else if (arr.length === 1){ return null; }else if (arr[index] < query) { arr = arr.slice(index + 1); let res = binarySearch(arr, query); if (res === null){ return -1; }else { return index + 1 + res; }; }else { let arr1 = arr.slice(0, index); return binarySearch(arr1, query); }; }; console.log(binarySearch(arr, 1)); console.log(binarySearch(arr, 7)); console.log(binarySearch(arr, 11)); console.log(binarySearch(arr, 12)); console.log(binarySearch(arr, 22));
Output
The output in the console −
0 5 7 -1 13
- Related Questions & Answers
- Searching for values in an Javascript Binary Search Tree
- Searching for minimum and maximum values in an Javascript Binary Search Tree
- Search in an array with Binary search using JavaScript
- Checking for univalued Binary Search Tree in JavaScript
- Set search feature in MySQL for full text searching
- Query MongoDB for a nested search
- Implementing a Binary Search Tree in JavaScript
- Binary Search Tree in Javascript
- Binary Search program in JavaScript
- 8085 program for Binary search
- Python Program for Binary Search
- C++ Program to Search for an Element in a Binary Search Tree
- Binary Search Tree Class in Javascript
- Java Program for Binary Search (Recursive)
- Python Program for Depth First Binary Tree Search using Recursion
Advertisements