• 折半 / 二分 查找


    折半查找,效率logn

    vs2010

    在一个有序数列中查找指定元素的方法

    // bsearch.cpp : 定义控制台应用程序的入口点。
    //
    
    #include "stdafx.h"
    
    #include <iostream>
    #include <vector>
    #include <cstdlib>
    #include <ctime>
    
    using namespace std;
    
    /**
        在一个已排序的向量中找到一个元素
        @param v 要查找的向量
        @param from 要查找的range的开头
        @param to 要查找的range的结尾
        @param a 要查找的元素
        @return 返回第一个匹配的值,否则返回-1
    */
    int binary_search(vector<int> v, int from, int to, int a)
    {
        if (from > to)
            return -1;
        int mid = ( from + to ) / 2;
        if ( v[mid] == a)
            return mid;
        else if (v[mid] < a)
            return binary_search( v, mid + 1, to, a );
        else 
            return binary_search( v, from, mid - 1, a);
    }
    
    /**
        打印向量中所有的元素
        @param a 要打印的向量
    */
    void print(vector<int> a)
    {
        for (int i = 0; i < a.size(); i++)
            cout << a[i] << " ";
        cout << "
    ";
    }
    /**
        设置要去随机数的种子
    */
    void rand_seed()
    {
        int seed = static_cast<int>(time(0));
        srand(seed);
    }
    /**
        计算一个range中的随机初始值
        @param a range的底部
        @param b range的顶部
        @return 返回一个随机数x, a <= x 并且 x <= b
    */
    int rand_int(int a, int b)
    {
        return a + rand() % (b - a + 1);
    }
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        rand_seed();
        vector<int> v(20);
        v[0] = 1;
        for (int i=1; i<v.size(); i++)
            v[i] = v[i -1] + rand_int(1, 10);
        print(v);
        cout << "Enter number to search for: ";
        int n;
        cin >> n;
        int j = binary_search(v, 0, v.size() - 1, n);
        cout << " Found in position " << j << "
    ";
        system("pause");
        return 0;
    }

  • 相关阅读:
    【后缀数组】poj2406 Power Strings
    [HNOI 2013]游走
    [HAOI 2008]木棍分割
    [SCOI 2010]传送带
    [SDOI 2010]魔法猪学院
    [Codeforces 235B]Let's Play Osu!
    [SPOJ 10628]Count on a tree
    [ZJOI 2010]count 数字计数
    [SHOI 2008]Debt 循环的债务
    [JSOI 2008]星球大战starwar
  • 原文地址:https://www.cnblogs.com/david-zhao/p/5073749.html
Copyright © 2020-2023  润新知