Skip to main content

Python program to visualize the behavior of upper_bound and lower_bound binary searches.

Project description

Binary Search Simulation

Python program to visualize the behavior of upper_bound and lower_bound binary searches.

Upper Bound Lower Bound
Intuitive Binary Search
Upper Bound Lower Bound
int upperBound(vector<int> &array, int target) {
  // array should be sorted in non-decreasing
  // order from left to right
  int l = 0, r = array.size() - 1;
  while (l <= r) {
    int mid = l + (r - l) / 2;
    if (target < array[mid]) {
      r = m - 1;
    } else {
      l = m + 1;
    }
  }
  return l;
}
int lowerBound(vector<int> &array, int target) {
  // array should be sorted in non-decreasing
  // order from left to right
  int l = 0, r = array.size() - 1;
  while (l <= r) {
    int mid = l + (r - l) / 2;
    if (target <= array[mid]) {
      r = m - 1;
    } else {
      l = m + 1;
    }
  }
  return l;
}
Binary Search Variation (works optimally for non-integer spaces)
Upper Bound Lower Bound
int upperBound(vector<int> &array, int target) {
  // array should be sorted in non-decreasing
  // order from left to right
  int l = -1, r = array.size();
  while (l + 1 < r) {
    int mid = l + (r - l) / 2;
    if (target < array[mid]) {
      r = m;
    } else {
      l = m;
    }
  }
  return r;
}
int lowerBound(vector<int> &array, int target) {
  // array should be sorted in non-decreasing
  // order from left to right
  int l = -1, r = array.size();
  while (l + 1 < r) {
    int mid = l + (r - l) / 2;
    if (target <= array[mid]) {
      r = m;
    } else {
      l = m;
    }
  }
  return r;
}

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

binarysearchsimulation-1.0.2.tar.gz (15.2 kB view hashes)

Uploaded Source

Built Distribution

binarysearchsimulation-1.0.2-py3-none-any.whl (16.0 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page