Binary search with returned index in STL?

前端 未结 6 1811
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-12 11:42

I need a binary search function.

I couldn\'t find any function in the standard library that will return the index of the found item, and if it wasn\'t found,

6条回答
  •  花落未央
    2021-01-12 12:18

    int a = 0, b = n-1;
    while (a <= b) {
        int k = (a+b)/2;
        if (array[k] == x) 
        {
            // x found at index k
        }
        if (array[k] < x) a = k+1;
        else b = k-1;
    }
    

提交回复
热议问题