C++实现二分查找
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++实现二分查找相关的知识,希望对你有一定的参考价值。
#include <iostream> using namespace std; #include <assert.h> //方法1:区间为[ ] /* int BinarySearch(int* a, int size, int x) { assert(a); int left = 0; int right = size - 1; while (left <= right) { int mid = left+(right - left) / 2; if (a[mid] < x) { left = mid + 1; } else if (a[mid] > x) { right = mid - 1; } else { return mid; } } return -1; }*/ //方法2:区间为[ ) int BinarySearch(int* a, int size, int x) { assert(a); int left = 0; int right = size; while (left < right) { int mid = left + (right - left) / 2; if (a[mid] < x) { left = mid + 1; } else if (a[mid] > x) { right = mid; } else { return mid; } } return -1; } void Test() { int array[] = {0, 1, 2, 3, 4, 5, 6, 7}; cout<<BinarySearch(array, sizeof(array)/sizeof(array[0]), 0)<<endl; } int main() { Test(); return 0; }
以上是关于C++实现二分查找的主要内容,如果未能解决你的问题,请参考以下文章