例题7-7 二分查找法之过程

算法本身不难,难的是细节,边界情况

【left,right】

int binarySearch(int nums[], int target) {
    int left = 0; 
    int right = nums.length - 1; // 注意

    while(left <= right) {
        int mid = left + (right - left) / 2;
        if(nums[mid] == target)
            return mid; 
        else if (nums[mid] < target)
            left = mid + 1; // 注意
        else if (nums[mid] > target)
            right = mid - 1; // 注意
    }
    return -1;
}

左闭右开 :【left,right)

int search(int nums[], int target) {
        int left = 0,right = nums.size();
        while(lefttarget){
                right = mid;
            }
        }
        return -1;
    }
};

最后给出该题我的代码

#include 
using namespace std;
bool isTurn(int a[], int n){
    for(int i=0;ia[j]) return false;
        }
    }
    return true;
}
bool isRepeat(int a[], int n){
    for(int i=0;i> n >> key;
    int a[10];
    for(int i=0;i> a[i];
    }
    if(isRepeat(a,n) || !isTurn(a,n)){
        cout << "Invalid Value";
        return 0;
    }
    int flag = 0;
    int left = 0, right = n-1;
    while(left <= right){
        int mid = left + (right-left)/2;
        printf("[%d,%d][%d]\n",left,right,mid);
        if(a[mid] > key) right = mid-1;
        else if(a[mid] < key) left = mid+1;
        else{
            flag = 1;
            cout << mid;
            break;
        }
    }
    if(!flag) cout << "Not Found";
    return 0;
}

你可能感兴趣的:(算法,c++)