- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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
Advertisements