1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40





//Find the first element which is equal or larger
//than the target
int SearchInsert(int A[], int n, int target) { 
    if(n==0)return 0;
    if(A[n-1] < target) return n;
    
    int low = 0;
    int high = n-1;
    int mid ;

    while(1)
    {
        mid = (low + high)/2;
        if(low >= high) break;
        if (A[mid] < target)
            low = mid +1;
        else
            high = mid;
    }

    return mid;
}



#include <iostream>

using namespace std;

int main(int argc, char** argv)
{
    int A[] = {2,3,5,7,11,13,17};
    int target = 8;
    cout << SearchInsert(A, 7, target);
    return 0;
}
View Program Text


Test Status