Williammer
4/7/2016 - 12:21 AM

Algorithm Search Implementations

Algorithm Search Implementations

function rotatedArrayMinBinarySearch(arr) {
  var len = arr.length,
    start = 0,
    end = len - 1,
    mid, min;

  // end edge: search range <= 1, no mid val in between.
  while (Math.floor((end - start) / 2) > 0) {
    mid = Math.floor((end - start) / 2);

    // rotated end val flags whether the shorter streak is on upper/lower frag, which contains the rotated point.
    if (arr[end] > arr[mid]) {
      // min should be in lower frag
      end = mid - 1;
      min = arr[mid];

    } else if (arr[end] < arr[mid]) {
      // min should be in lower frag
      start = mid + 1;
      min = arr[end];

    } else {
      // can't be equal
      return -1;
    }

  }
  return min;
}
var mmm = rotatedArrayMinBinarySearch([5, 6, 7, 8, 9, 1, 2, 3, 4]);
document.body.innerHTML = mmm;
function binSearch(arr, data) {
  var upperBound = arr.length - 1;
  var lowerBound = 0;
  while (lowerBound <= upperBound) {
    var mid = Math.floor((upperBound + lowerBound) / 2);
    if (arr[mid] < data) {
      lowerBound = mid + 1;
    } else if (arr[mid] > data) {
      upperBound = mid - 1;
    } else {
      return mid;
    }
  }
  
  
  return -1;
}