C++二分查找算法实例

时间:2022-11-25 15:46:24

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#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;
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://www.cnblogs.com/lucy-lizhi/p/7381306.html