C++二分查找算法实例
时间:2021-03-03 10:05:40|栏目:C代码|点击: 次
本文实例为大家分享C++二分查找算法,通过改变边界位置来进行查找的方法,代码如下:
#include <iostream> using namespace std; int search(int *p,int length,int key); int search1(int *p,int length,int key); int main() { cout << "Hello world!" << endl; int a[] = {1,2,3,4,5,6,7,8,8,8,9,10,11,12,13,14}; int len = sizeof(a)/sizeof(int); int pos = search1(a,len,8); cout << pos << endl; return 0; } int search1(int *p,int length,int key) { int left=0; int right=length-1; while(left<=right) { int mid = (left+right)/2; if(p[mid]>=key) { right = mid-1; }else { left = mid+1; } } if(left<length && p[left]==key) return left; return -1; } int search(int *p,int length,int key) { int left=0; int right = length -1; while(left<=right) { int mid = (left+right)/2; if(p[mid]==key) { return mid; } if(p[mid] > key) { right = mid+1; } if(p[mid]<key) { left=mid-1; } } return -1; }