What is the best way to search for an item in a sorted list in JavaScript?

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

As far as sorted arrays are concerned (be it in any order), binary search is the most optimized and efficient search algorithm to exist. We are required to write a binary search function that searches a sorted array of literals for a target.

We should then attach that function to the prototype property of Array Objects.

Example

The code for this will be −

const arr = [2, 5, 8, 12, 14, 16, 17, 22, 26, 28, 35, 67, 78, 99];
const target = 22;
Array.prototype.binarySearch = function(target) {
   if ( !this.length ) { return false; }
   if ( this[0] === target ) { return true; }
   var i, mid,
      start = 0,
      end = this.length,
      c = false;
   while ( c = (i = this[mid = start+((end-start)>>1)]) !== target ) {
      i < target ? (start = mid) : (end = mid);
      if (start >= end - 1) { break; }
   }
   return !c;
};
console.log(arr.binarySearch(target));

Output

And the output in the console will be −

true
raja
Published on 23-Nov-2020 12:17:28
Advertisements