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

    /*算法描述:来自《算法分析与设计》 代码来自网络QAQ*/
    /*
    * 输入:n个元素的升序数组A[1,...,n]和元素x
    * 输出:如果x = A[j], 1<=j<=n,则输出j, 否则输出0
    * low <- 1; high <- n; j <- 0
    * while (low<=high) and (j=0)
    *     mid <- (low+high)/2
    *     if x = A[mid] then j <- mid
    *     else if x < A[mid] then high <- mid-1
    *     else low <- mid+1
    * end while
    * return j
    */
    //非递归
    int BinarySearch(int *A, int aSize, int key)
    {
        if ( A == NULL || aSize == 0)
            return -1;
        int low = 0;
        int high = aSize - 1;
        int mid = 0;
    
        while (low <= high)
        {
            mid = (low + high)/2;
            if (A[mid] < key)
                low = mid + 1;
            else if (A[mid] > key)
                high = mid - 1;
            else
                return mid;
        }
        return -1;
    }
    
    //递归
    int BinarySearchRecursive(int *A, int low, int high, int key)
    {
        if (low > high)
            return -1;
        int mid = (low + high)/2;
        if (A[mid] == key)
            return mid;
        else if (A[mid] < key)
            return BinarySearchRecursive(A, mid+1, high, key);
        else
        {
            return BinarySearchRecursive(A, low, mid-1, key);
        }
        
    }
    
    int main()
    {
        int A[10];
        for (int i=0; i<10; i++)
            A[i] = i;
        cout << "No recursive:" << endl;
        cout << "position:"<< BinarySearch(A, 10, 6) << endl;
        cout << "recursive:" << endl;
        cout << "position:" << BinarySearchRecursive(A, 0, 9, 6) << endl;
    
        return 0;
  • 相关阅读:
    HTML5第二节
    HTML5在移动端开发的12大特性
    移动端开发遇到的坑
    html5 meta(移动端)介绍及使用
    CSS的margin塌陷(collapse)
    Block Demo
    设计模式之代理
    OC Block网上转载
    GCD之全局、主线程
    Spark SQL中 RDD 转换到 DataFrame
  • 原文地址:https://www.cnblogs.com/harbin-ho/p/12656908.html
Copyright © 2011-2022 走看看