First look at the general wording of the binary search
#include <stdio.h> #include <math.h> #include <string.h> #include <stdlib.h> #include < Algorithm> #include <vector>using namespace std; #define N 100005#define ll __int64int n,a[n];int findd (int x) { int l=0,r=n-1; while (l<=r) { int mid= (l+r) >>1; if (a[mid]==x) return mid; if (a[mid]>x) r=mid-1; else l=mid+1; } return-1; }int Main () { int i,m,x,t not found; while (~SCANF ("%d", &n)) {for (i=0;i<n;i++) { scanf ("%d", &a[i]); } Sort (a,a+n); scanf ("%d", &m); while (m--) { scanf ("%d", &x); T=FINDD (x); printf ("%d\n", t); } } return 0;}
A generic binary lookup can only find the target value, but the subscript returned when the target value repeats appears is indeterminate, and the following notation returns the subscript for the first occurrence of the target value. When the target value does not appear, returns the subscript of the element that is larger than the target value or returns the boundary value N;
#include <stdio.h> #include <math.h> #include <string.h> #include <stdlib.h> #include < Algorithm> #include <vector>using namespace std; #define N 100005#define ll __int64int n,a[n];int findd (int x) { C0/>int l=0,r=n-1; while (l<=r) { int mid= (l+r) >>1; if (a[mid]>=x) r=mid-1; else l=mid+1; /*if (a[mid]<x) //This writing also above the same effect l=mid+1; else r=mid-1;*/ } return l; Returns the subscript for the target value, and returns the first occurrence of the subscript if more than one value is the same. }int Main () { int i,m,x,t; while (~SCANF ("%d", &n)) {for (i=0;i<n;i++) { scanf ("%d", &a[i]); } Sort (a,a+n); scanf ("%d", &m); while (m--) { scanf ("%d", &x); T=FINDD (x); printf ("%d\n", t); } } return 0;}
Two-point Search summary