二分查找
Posted 略加思索的河马
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二分查找相关的知识,希望对你有一定的参考价值。
#include <iostream> using namespace std; //常规方式 int binary_find(vector<int> &data, int num) { int low = 0; int high = data.size() - 1; while (low <= high) { int mid = low + (high - low) / 2; if (num == data[mid]) { return mid; } else if (num < data[mid]) { high = mid - 1; } else { low = mid + 1; } } return -1; } //递归方式 int binary_find(vector<int> &data, int low, int high, int num) { if (low > high) return -1; int mid = low + (high - low) / 2; if (num == data[mid]) { return mid; } else if (num < data[mid]) { binary_find(data, low, mid - 1, num); } else { binary_find(data, mid + 1, high, num); } } int main() { int a[] = {1, 2, 3, 4, 6, 7, 8, 9, 100, 10000}; vector<int> test_vector(a, a+10); int i = binary_find(test_vector, 10000); cout << i << endl; getchar(); return 0; }
以上是关于二分查找的主要内容,如果未能解决你的问题,请参考以下文章