• 折半查找


    阿里笔试的时候考了,回来写了下。

    #include <iostream>
    
    using namespace std;
    
    
    
    int BinarySearch(int array[], int lenght, int key)
    {
        
        
        int low = 0; 
        int high = lenght - 1;
        int mid;
        while (low <= high){
            mid = (low + high)/2;
            if(array[mid] == key){
                
                printf("%d
    ",array[mid]);
                return array[mid];
                }
            else if(array[mid] > key)
                high = mid - 1;
            else 
                low = mid + 1;
        }
         
        return -1;
    }
    
    
    void test0()
    {
        int array[10] = {0,1,2,3,4,5,6,7,8,9};
        if(BinarySearch(array, 10, 5) == 5)
        {
            printf("-------------------------passed
    ");
        }
        else
        {
            printf("-------------------------failed
    ");
        }    
    }
    
    void test1()
    {
        int array[10] = {0,1,2,3,4,5,6,7,8,9};
        if(BinarySearch(array, 10, 15) == -1)
        {
            printf("-------------------------passed
    ");
        }
        else
        {
            printf("-------------------------failed
    ");
        }    
    }
    void test2()
    {
        int array[1] = {0};
        if(BinarySearch(array, 1, 15) == -1)
        {
            printf("-------------------------passed
    ");
        }
        else
        {
            printf("-------------------------failed
    ");
        }    
    }
    void test3()
    {
        int array[1] = {0};
        if(BinarySearch(array, 1, 0) == 0)
        {
            printf("-------------------------passed
    ");
        }
        else
        {
            printf("-------------------------failed
    ");
        }    
    }
    void test4()
    {
        int array[10] = {0,1,2,3,4};
        if(BinarySearch(array, 5, 4) == 4)
        {
            printf("-------------------------passed
    ");
        }
        else
        {
            printf("-------------------------failed
    ");
        }    
    }
    int main()
    {
        test0();
        test1();
        test2();
        test3();
        test4();
    }
    ________你所记的,都是假的。
  • 相关阅读:
    WP2Sinablog使用后的后遗症
    .NET Framework 4 与 .NET Framework 4 Client Profile
    360浏览器也有了开发人员工具了
    让你的手机号“变”qq号
    首次体验 Live Writter
    判断素数
    SqlServer文件挂起
    vni—2015:验证错误
    成功者善于模仿(转)
    dbms_output缓冲区溢出
  • 原文地址:https://www.cnblogs.com/pudding-ai/p/3676741.html
Copyright © 2020-2023  润新知