Saturday, March 27, 2021

binary search

 Here a simple binary search works with typescript.  The following conditions before the search start using binary search technique starts.  The search list should be sorted else  this technique is not effective at all. why because this technique basically narrows down the result set to search let say if you a list [2,4,6,8,10] first the technique will start from the middle of the list which is 6 in the list and index is 3. The algorithm will compare with number to be searched whether it's larger or smaller or equal. if searched number is smaller than 6 then we assume the searched number lies between index 0 and index 2. So search list is narrowed to indexes between 0 and 2. If the searched number is greater than 6 then we assume the searched number lies between index 3 and 4 so the search is narrowed to searching the indexes between 3 and 4. The list narrows down after each iteration either possibly finding the right index or terminating the search. The terminating the left hand side should be less than or equal to right.


class binarySearch {
  list = [];
   left = 0;
   right = 0;
  no: number;
  private index : number=0;
  findNumber() {
    console.clear();
    if(this.list.length ==0 || this.no == undefined)
      return
    while (this.left <= this.right) {
       var middle = Math.trunc(Math.floor(this.left+this.right)/2);
       console.log(middle,this.left,this.right)

      //conditions begin
      if (this.list[middle]<this.no)
          this.left = this.left+1;
      if(this.list[middle]>this.no)    
          this.right = this.right-1;
      if(this.list[middle]==this.no || this.index> this.list.length)    
      {
        console.log(middle,this.list[middle])
        break;
      }
      this.index++;
    }
  }
}
var bs  = new binarySearch();
bs.list=[4,7,8,9,10,11,12,99as any;
bs.no = 4;
bs.left = 0;
bs.right=bs.list.length-1;
bs.findNumber();


No comments:

Post a Comment