简单实现二分查找

 

#include

int _do_while(int &start, int &end, int &want){
    int mid;
    do {
        mid = (start + end) / 2;
        if (want == mid){
            std::cout << "\n\ndo_while!\n";
            printf("%d Adress: %p\n", want, want);
            break;
        }
        else if (want > mid)
            start = mid + 1;
        else
            end = mid - 1;    
    } while (start < end);
    return want;
}

int _while(int &start, int &end, int &want){
    int mid;
    while (start < end){
        mid = (start + end) / 2;
        if (want == mid){
            std::cout << "\n\nwhile!\n";
            printf("%d Adress: %p\n", want, want);
            break;
        }
        else if (want > mid)
            start = mid + 1;
        else
            end = mid - 1;
    }
    return want;
}

int _go_to(int &start, int &end, int &want){
    int mid=0;
Loop:
    if (want != mid){
        mid = (start + end) / 2;
        if (want > mid)
            start = mid + 1;
        else 
            end = mid - 1;
        goto Loop;
    }
     std::cout << "\n\ngoto!\n";
     printf("%d Adress:%p\n", want, want);
     return want;
}

int _R(int &start, int &end, int &want){
    if (start < end){
        int mid = (start + end) / 2;
        if (want == mid) {
            std::cout << "\n\nrecursive \n";
            printf("%d adress: %p\n", want, want);
        }
        else {
            if (want > mid) { 
                start = mid + 1; 
                _R(start, end, want); 
            }else { 
                end = mid - 1; 
                _R(start, end, want); 
            }
        }return want;
    }
    return want;
}


int main(){
    int s = 0, end = 1024*10^10,target=99;

    std::cout << "please input two numbers as boundary\n";
    std::cin >> s >> end;
    std::cout << "input the target number \n";
    std::cin >> target; 
    std::cout << std::endl;

    if (target < s || target >end)
        return 0;
    
    _while(s, end, target);
    _do_while(s, end, target);
    _R(s, end, target);//Recursion
    _go_to(s, end, target);
    
    return 0;

}

 

你可能感兴趣的:(算法学习,学习)