ACM: binary search, and upper and lower bounds using the bipartite search

Source: Internet
Author: User

(1) binary template:

int binary_search(int *array, int length, int key) {int start = 0, end = length - 1;while(end >= start) {int middle = start + (end - start) / 2;int tmp = array[middle];if(tmp < key) start = middle + 1;else if (tmp > key) end = middle - 1;else return middle;}return -1;}

(2)

#include
 
  #includeint A[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};int bsearch(int* A, int x, int y, int v) {  int m;  while(x < y) {    m = x+(y-x)/2;    if(A[m] == v) return m;    else if(A[m] > v) y = m;    else x = m+1;  }  return -1;}int main() {  int i;  for(i = 1; i <= 11; i++)    assert(bsearch(A, 0, 11, i) == i-1);  printf("Ok!\n");  return 0;}
 

(3) Finding the upper and lower bounds using the bipartite Method

#include
 
  #include#include 
  
   using namespace std;int A[] = {1, 2, 3, 3, 3, 3, 3, 5, 6};int lower_bound(int *array, int length, int v) {  int start = 0, end = length - 1;  while(start <= end) {    int middle = start + (end - start) / 2;    int tmp = array[middle];    if(array[middle] >= v) end = middle - 1;     else start = middle + 1;  }  return start;}int upper_bound(int *array, int length, int v) {  int start = 0, end = length-1;  while(start <= end) {    int middle = start + (end - start) / 2;    int tmp = array[middle];    if(array[middle] <= v) start = middle + 1;     else end = middle - 1;  }  return start;}int main() {  cout << lower_bound(A, 9, 3) << endl    << upper_bound(A, 9, 3) << endl;  return 0;}
  
 


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.