zoukankan      html  css  js  c++  java
  • 二分查找法

    分别用循环和递归实现二分查找

    #include <iostream>
    using namespace std;
    int binarysearchiteratively(int *data, int start, int end, int k){
        int l = start - 1;
        int r = end + 1;
        while (l + 1 != r){
            int middle = (l + r) / 2;
            if (data[middle] == k) return middle;
            else{
                if (data[middle] < k) l = middle;
                else{
                    r = middle;
                }
            }
        }
        return -1;
    }
    int binarysearchrecursively(int *data, int start, int end, int k){
        if (start>end) return -1;
        int middle = (start + end) / 2;
        if (data[middle] == k){
            return middle;
        }
        else{
            if (data[middle] < k){
                return binarysearchrecursively(data,middle+1,end,k);
            }
            else{
                return  binarysearchrecursively(data, start, middle - 1, k);
            }
        }
    
    }
    void test1(){
        int a[] = { 1, 2, 3 };
        int result1 = binarysearchiteratively(a, 0, 2, 1);
        int result2 = binarysearchrecursively(a, 0, 2, 1);
        if (result1 == 0 && result2 == 0){
            printf("%s
    ", "test1 succeeded");
        }
        else{
            printf("%s
    ", "test1 failed");
        }
    }
    void test2(){
        int a[] = { 1, 2, 3 };
        int result1 = binarysearchiteratively(a, 0, 2, 4);
        int result2 = binarysearchrecursively(a, 0, 2, 4);
        if (result1 == -1 && result2 == -1){
            printf("%s
    ", "test2 succeeded");
        }
        else{
            printf("%s
    ", "test2 failed");
        }
    }
    void test3(){
        int a[] = { 1 };
        int result1 = binarysearchiteratively(a, 0, 0, 1);
        int result2 = binarysearchrecursively(a, 0, 0, 1);
        if (result1 == 0 && result2 == 0){
            printf("%s
    ", "test3 succeeded");
        }
        else{
            printf("%s
    ", "test3 failed");
        }
    }
    void test4(){
        int a[] = { 1 };
        int result1 = binarysearchiteratively(a, 0, 0, 2);
        int result2 = binarysearchrecursively(a, 0, 0, 2);
        if (result1 == -1 && result2 == -1){
            printf("%s
    ", "test4 succeeded");
        }
        else{
            printf("%s
    ", "test4 failed");
        }
    }
    int main(){
        test1();
        test2();
        test3();
        test4();
        system("pause");
    }
  • 相关阅读:
    python libsvm模块在mac上的安装
    logistic regression (Python&Matlab实现)
    读C++ primer 的一些练习
    R笔记
    python学习笔记
    linux常用命令
    macbook air安装ubuntu双系统简记
    解方程——对分法
    解方程——不动点迭代
    隐马尔可夫模型模型评估及最优路径的matlab实现
  • 原文地址:https://www.cnblogs.com/hzmbbbb/p/3980590.html
Copyright © 2011-2022 走看看