zoukankan      html  css  js  c++  java
  • 算法-对分查找(二分查找)C++实现

    这个是个主要的查找算法。由于仅仅是把数读入就须要(N)的时间量,因此我们在说这类问题的时候都是如果读入过的。

    在算法经常使用的时间。将问题缩小为一部分(大约1/2),那么我们就觉得这个算法是O(logn)级别的。


    先说下对分查找的时间复杂度为O(logn)

    前提是已经拍序好的数列。


    //
    //  main.cpp
    //  binarySearch
    //
    //  Created by Alps on 14-7-24.
    //  Copyright (c) 2014年 chen. All rights reserved.
    //
    
    #include <iostream>
    
    int binarySearch(const int A[], int X, int N){
        int start = 0, end = 0, mid;
        end = N;
        while (start <= end) {
            mid = (start + end)/2;
            if (X > A[mid]) {
                start = mid+1;
                continue;
            }else if (X < A[mid]){
                end = mid-1;
                continue;
            }else{
                return mid;
            }
        }
        return -1;
    }
    
    int main(int argc, const char * argv[])
    {
        int A[]={1 ,4 , 6, 8, 19, 34, 93};
        int N = sizeof(A)/sizeof(int);
        int X = 19;
        
        int locate = binarySearch(A, X, N);
        if (locate == -1) {
            printf("Can't find the element %d
    ",X);
        }else{
            printf("The element %d is locate in %d
    ",X,locate);
        }
        
        return 0;
    }
    

    这里面没什么原理。

    。问题非常easy~ 

  • 相关阅读:
    洛谷P3953 逛公园
    洛谷P1247 取火柴游戏
    洛谷P2024 食物链
    洛谷P2680 运输计划
    hdu 1495 非常可乐(bfs)
    poj3984 迷宫问题(简单的输出路径的bfs)
    Codeforces 729C Road to Cinema(二分)
    Codeforces Technocup 2017
    Codeforces Technocup 2017
    poj 2251 Dungeon Master(bfs)
  • 原文地址:https://www.cnblogs.com/liguangsunls/p/7050195.html
Copyright © 2011-2022 走看看