您的位置:首页 > 编程语言 > C语言/C++

c++ 计蒜客挑战难题第10题寻找插入位置 二分查找

2015-07-21 11:55 603 查看
#include <iostream>

using namespace std;

int searchInsert(int a[],int n,int target)

{
int min = 0, max = n-1, mid;
while (min < max) {
mid = (max+min) >> 1;
if (target > a[mid])
min = mid+1;

        else if (target == a[mid])

            return mid;
else 
max = mid;

}

    if (target > a[n-1])

        return n;
return min;

}

int main()

{
int t, n, target = 0;

    cin >> n;
int *a = new int
;

    

    for (int i = 0; i < n ; i++)
cin >> a[i];
cin >> target;

    

    cout << searchInsert(a,n,target);
return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: