• 二分查找法


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

    #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");
    }
  • 相关阅读:
    小村系列之十八:幸福的桥
    小村系列之十六:改革的石头
    获取<select>,<radio>,<checkbox>中未被选中的value值和被选中的value值
    display:inline-block,block,inline的区别与用法
    Java中List Set Map集合的遍历
    C#自定义List类
    C#获取文件和文件夹大小
    C# winform带进度条的图片下载
    C#委托的详细使用
    asp.net cookie和session的详细使用
  • 原文地址:https://www.cnblogs.com/hzmbbbb/p/3980590.html
Copyright © 2020-2023  润新知