zoukankan      html  css  js  c++  java
  • 数据结构-二分查找

     1 #include <iostream>
     2 #include <algorithm>
     3 #include <vector>
     4 #include "example_vec.h"
     5 #include "printCollection.h"
     6 using namespace std;
     7 
     8 extern vector<int> example_vec;
     9 
    10 template<typename comparable>
    11 int binarySearch(const vector<comparable> &a, const comparable &x){
    12     int low = 0, high = a.size() - 1;
    13 
    14     while(low <= high)
    15     {
    16         int center = (high + low)/2;
    17         if(x < a[center])
    18             high = center - 1;
    19         else if(x > a[center])
    20             low = center + 1;
    21         else
    22             return center;
    23     }
    24 
    25     return -1;
    26 }
    27 int main(){
    28 
    29     cout << "The count of array is: " << example_vec.size() << endl;
    30 
    31     printCollection(example_vec);
    32 
    33     stable_sort(example_vec.begin(), example_vec.end());
    34 
    35     printCollection(example_vec);
    36 
    37     cout << "The index of 13 is " << binarySearch(example_vec, 13) << endl;
    38 
    39     return 0;
    40 
    41 }
  • 相关阅读:
    为zabbix穿上一件漂亮的外衣
    CentOS7 Ceph分布式集群部署
    SSH 免秘钥登录
    zabbix监控Tomcat/JVM 实例性能
    zabbix 监控 IPMI
    2装饰者模式
    1代理模式
    3单例模式
    2抽象工厂模式
    1工厂模式
  • 原文地址:https://www.cnblogs.com/dracohan/p/3825842.html
Copyright © 2011-2022 走看看