- 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
Binary Search program in JavaScript
Create a function, say binarySearch() that takes in 4 arguments −
- a sorted Number / String literal array
- starting index of array (0)
- ending index of array (length - 1)
- number to be searched
If the number exists in the array, then the index of the number should be returned, otherwise -1 should be returned. Here is the full code −
Example
const arr = [2,4,6,6,8,8,9,10,13,15,17,21,24,26,28,36,58,78,90]; //binary search function //returns the element index if found otherwise -1 const binarySearch = (arr, start, end, num) => { const mid = start + Math.floor((end - start)/2); if(start <= end){ if(arr[mid] === num){ return mid; } if(num < arr[mid]){ return binarySearch(arr, start, mid-1, num); } if(num > arr[mid]){ return binarySearch(arr, mid+1, end, num); } } return -1; }; console.log(binarySearch(arr, 0, arr.length-1, 13)); console.log(binarySearch(arr, 0, arr.length-1, 11));
Output
The output of this code in the console will be −
8 -1
Advertisements