C++二分查找算法实例

本文实例为大家分享C++算法" title="查找算法">查找算法" title="二分查找算法">二分查找算法,通过改变边界位置来进行查找的方法,代码如下:

#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;

}

以上是 C++二分查找算法实例 的全部内容, 来源链接: utcz.com/z/333516.html

回到顶部