Binary Search and Binary Search

Source: Internet
Author: User

Binary Search and Binary Search

/* Binary Search for Common bs (); Lower Bounds low_bs (); upper bounds up_bs (); */# include <cstdio >#include <algorithm> using namespace std; // [l, r) int bs (int * T, int l, int r, int v) {int m; while (l <r) {m = l + (r-l)/2; // note> 1. Enclose if (T [m] = v) return m; if (T [m] <v) l = m + 1; else r = m;} return-1; //-1 indicates not found} // The first subscript l with the search value of v // indicates the range of the lower bound [l, r) from [l, r, r] int low_bs (int * T, int l, int r, int v) {int m; while (l <r) {m = l + (r-l) /2; if (T [m]> = v) r = m; else L = m + 1;} return l;} // returns a subscript r int up_bs (int * T, int l, int r, int v) after the last element of v) {int m; while (l <r) {m = l + (r-l)/2; if (T [m] <= v) {l = m + 1;} else {r = m ;}} int a [100]; int main () {int n; scanf ("% d ", & n); for (int I = 0; I <n; I ++) scanf ("% d", & a [I]); int v; scanf ("% d", & v); sort (a, a + n); // dont forget !! Printf ("a location of this element is % d \ n", bs (a, 0, n, v); printf ("[% d, % d] ", low_bs (a, 0, n, v), up_bs (a, 0, n, v)-1); // STLscanf (" % d ", & n); for (int I = 0; I <n; I ++) scanf ("% d", & a [I]); sort (, a + n); scanf ("% d", & v); printf ("lower_bound = % d \ nupper_bound = % d \ n", lower_bound (a, a + n, v)-a, upper_bound (a, a + n, v)-a); return 0 ;}



Refer to Liu rujia <getting started classic>

Related Article

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.