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 }
  • 相关阅读:
    ASP.NET Core 静态资源的打包与压缩
    算法
    字符串反转
    js 获取随机数
    AspNetCore MVC 跨域
    add digits
    1-bit and 2-bit Characters
    删除字符串中出现次数最少的字符
    洗牌
    哈夫曼编码
  • 原文地址:https://www.cnblogs.com/dracohan/p/3825842.html
Copyright © 2011-2022 走看看