zoukankan      html  css  js  c++  java
  • 折半查找

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

    #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();
    }
    ________你所记的,都是假的。
  • 相关阅读:
    subtext 安装PythonIDE -Anaconda
    Python--DBUtil
    python操作oracle数据库-查询
    Python 离线工作环境搭建
    Scrapy-下载中间件
    centos安装 Anaconda3及使用
    Scrapy爬取人人网
    海明距离
    中心极限定理
    最大似然估计 (MLE)与 最大后验概率(MAP)在机器学习中的应用
  • 原文地址:https://www.cnblogs.com/pudding-ai/p/3676741.html
Copyright © 2011-2022 走看看