本文实例为大家分享C++二分查找算法,通过改变边界位置来进行查找的方法,代码如下: #include iostreamusing namespace std;int search(int *p,int length,int key);int search1(int *p,int length,int key);int main
本文实例为大家分享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; }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自由互联。