binary_search

来源:互联网 发布:游戏王 知乎 编辑:程序博客网 时间:2024/04/27 22:42

二分查找

#include <iostream>

#include <algorithm>
#include <cstdio>
#include <vector>
using namespace std;


bool myfunction (int i,int j) { return (i<j);}


int main () {
  int myints[] = {9,2,3,4,5,4,3,2,1};
  vector<int> v(myints,myints+9);                       // 1 2 3 4 5 4 3 2 1


  // using default comparison:
  sort (v.begin(), v.end());


  cout << "looking for a 3...";
  if (binary_search (v.begin(), v.end(),3))
    cout <<"found!\n"; else cout << "not found.\n";


  // using myfunction as comp:
  sort (v.begin(), v.end(), myfunction);


  cout << "looking for a 6...";
  if (binary_search (v.begin(), v.end(), 1,myfunction))
    cout <<"found!\n"; else cout << "not found.\n";
    for(int i=0;i<9;i++)
    printf("%d ",myints[i]);


  return 0;
}

binary_search二分法怎样使用?

二分法检索又称折半检索,二分法检索的基本思想是设字典中的元素从小到大有序地存放在数组中,首先将给定值key与字典中间位置上元素的关键码比较,如果相等,则检索成功;否则,若key小,则在字典前半部分中继续进行二分法检索,若key大,则在字典后半部分中继续进行二分法检索。这样,经过一次比较就缩小一半的检索区间,如此进行下去,直到检索成功或检索失败。二分法检索是一种效率较高的检索方法,要求字典在顺序表中按关键码排序。

binary_search

原型:

 #include <algorithm>
 bool binary_search( forward_iterator start, forward_iterator end, constTYPE& val );
 bool binary_search( forward_iterator start, forward_iterator end, constTYPE& val, Comp f );

返回值:

true if an element is found in the rangethat is equal or equivalent to the specified value; otherwise, false.

代码演示:

#include <algorithm>

int main()
{
    int nums[] = { -242, -1, 0, 5, 8, 9, 11 };//
必须按递增顺序排列
    int start = 0; int end = 7;  
    for( int i = 0; i < 10; i++ ) 
    {
        if( std::binary_search( nums+start,nums+end, i ) )//
如果找到返回TRUE,没有找到则返回FALSE
        {
           printf("
找到\n");
        }
        else 
        {
           printf("
没找到\n");
        }
    }
    return 0;
}

附注1:数组必须是按递增顺序排列的,否则错误

更详细的可参考MSDN,以及上面所列举的一个例子

原创粉丝点击