二分搜索之C++实现
一、源代码:BinarySearch.cpp
1 #include<iostream>
2 using namespace std;
3
4 /*定义输出一维数组的函数*/
5 void print(int array[], int n)
6 {
7 for (int i = 0; i < n; i++)
8 {
9 cout << array[i] << " ";
10 }
11 cout << endl;
12 }
13
14 /*定义二分搜索的函数:array,有序序列;n,序列长度;x,要查找的数*/
15 int binarySearch(int array[], int n, int x)
16 {
17 //初始化左右边界
18 int left = 0, right = n - 1;
19 //当左右边界不重合时
20 while (left <= right)
21 {
22 //初始化边界的中点
23 int middle = (left + right) / 2;
24 //判断所查找元素和当前中点元素是否相等,如果相等则返回中点元素所在的位置
25 if (x == array[middle])
26 {
27 return middle;
28 }
29 else if (x > array[middle])
30 {
31 //如果所查找元素大于中点元素,则所查找元素在右部分,则将左边界向右移
32 left = middle + 1;
33 }
34 else{
35 //说明所查找元素小于中点元素,则所查找元素在做部分,则将右边界向左移
36 right = middle - 1;
37 }
38 }
39 //如果找不到,则返回-1
40 return -1;
41 }
42 int main()
43 {
44 //定义待排序的一维数组
45 int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
46 //输出原始数组
47 cout << "原始数组是:" << endl;
48 print(array, 10);
49 //定义要查找的数
50 int number;
51 //输入要查找的数
52 cout << "请输入要查找的数:";
53 cin >> number;
54 //调用二分搜索的函数进行查找
55 int location = binarySearch(array, 10, number);
56 if (location > 0)
57 {
58 //说明找到了
59 cout << number << "在该序列中,是第" << (location + 1) << "个数" << endl;
60 }
61 else
62 {
63 //说明没找到
64 cout << number << "不在该序列中..." << endl;
65
66 }
67 return 0;
68 }
二、运行效果
在序列中
不在序列中
原文链接: https://www.cnblogs.com/zfc-java/p/7392446.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/258528
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!