JavaScript Implementation of Binary Lookup Instance Code

  • 2021-07-22 08:53:47
  • OfStack

The premise of 2-point search is: array and order. The logic is: preferentially compare with the intermediate element of the array, and if it is equal to the intermediate element, it will return directly. If not, take half and continue searching.


/**
 * 2 Sub-search, recursive realization. 
 * @param target
 * @param arr
 * @param start
 * @param end
 * @returns {*}
 */
function binarySearch(target,arr,start,end) {
  var start  = start || 0;
  var end   = end || arr.length-1;
  var mid = parseInt(start+(end-start)/2);
  if(target==arr[mid]){
    return mid;
  }else if(target>arr[mid]){
    return binarySearch(target,arr,mid+1,end);
  }else{
    return binarySearch(target,arr,start,mid-1);
  }
  return -1;
}
/**
 *  Orderly 2 Split search, return -1 Or an array subscript that exists. No recursive implementation is used. 
 * @param target
 * @param arr
 * @returns {*}
 */
function binarySearch(target,arr) {
  var start  = 0;
  var end   = arr.length-1;
  while (start<=end){
    var mid = parseInt(start+(end-start)/2);
    if(target==arr[mid]){
      return mid;
    }else if(target>arr[mid]){
      start  = mid+1;
    }else{
      end   = mid-1;
    }
  }
  return -1;
}

After writing orderly, I naturally thought of how to use 2 points to find out the disorder. Immediately think of using fast-row grouping first, divide the group and then score 2 points. The code is as follows:


/**
 *  Disordered 2 Separate search. Return true/false
 * @param target
 * @param arr
 * @returns {boolean}
 */
function binarySearch(target,arr) {
  while (arr.length>0){
    // Use a quick sort. With mid Divide the size for the center, small on the left and large on the right. 
    var left  = [];
    var right  = [];
    // Select 1 Elements as base elements ( Baseline elements can be arbitrary 1 Elements )
    var pivot  = arr[0];
    // Because of taking the number 1 Elements, so from the first 2 Elements start the loop 
    for(var i=1;i<arr.length;i++){
      var item = arr[i];
      // Those larger than the reference are placed on the right and those smaller than the reference are placed on the left 
      item>pivot ? right.push(item) : left.push(item);
    }
    // Get a new sorted array 
    if(target==pivot){
      return true;
    }else if(target>pivot){
      arr   = right;
    }else{
      arr   = left;
    }
  }
  return false;
}

After writing the disordered 2-point search realized by quick sorting, I carefully thought about the time complexity of this algorithm, and found that it is not as fast as a direct for cycle


Related articles: