有序数组查找第一个比k大的数

/*有序数组,查找第一个大于k的数*/

#include

using namespace std;

int find_first_larger_than_k(int* list, int len, int k){
    if (list == NULL || len <= 0 || list[len - 1] <= k){
        return -1;
    }

    int l = 0;
    int r = len - 1;
    int res = len - 1;

    while(l < r){
        int mid = (l + r)/2;
        if(list[mid] > k){
            r = mid - 1;
            res = mid;
        }else{
            l = mid + 1;
        }
    }
    return res;
}

int main(){
    int list[5] = {1,2,3,4,5};
    int n = 5;
    //int list[] = {};
    for(int i = 0; i < n ; ++i){
        cout << list[i]<< " ";
    }
    cout << endl;
    int key;
    cin >> key;
    int index = find_first_larger_than_k(list, n, key);
    cout << "find index: "<< index << endl;
    return 0;
}

你可能感兴趣的:(c++基础排序和算法)