C++二分查找算法实例 C++二分查找算法实例
^~~^ 人气:0想了解C++二分查找算法实例的相关内容吗,^~~^在本文为您仔细讲解C++二分查找算法实例的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点: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; }
加载全部内容