有序序列的查找
【摘要】
#include "stdio.h"
#include<iostream>
#define MAX 100
using namespace std;
int Binary_Search(con...
#include "stdio.h"
#include<iostream>
#define MAX 100
using namespace std;
int Binary_Search(const int* array, int n, int key)
{
int low = 1;
int high = n;
int mid;
while (low <= high)
{
if (array[0] < array[1])
{
mid = (low + high) / 2;
if (key < array[mid])
high = mid - 1;
else if (key > array[mid])
low = mid + 1;
else
return mid;
}
if (array[0] > array[1])
{
mid = (low + high) / 2;
if (key > array[mid])
high = mid - 1;
else if (key < array[mid])
low = mid + 1;
else
return mid;
}
}
return 0;
}
int main()
{
int MAXSIZE;
int key;
cout << "请输入序列的大小: ";
cin >> MAXSIZE;
int num[MAX];
cout << "请输入一个有序序列:本程序仅可实现有序序列的查找(即递增或递减)\n";
for (int i = 0; i < MAXSIZE; i++)
{
cin >> num[i];
}
cout << '\n' << "请输入关键字= ";
cin >> key;
cout << endl;
int key_find = Binary_Search(num, MAXSIZE, key);
if (key_find == 0)
cout << "没找到!";
else
cout << key << "在序列的第" << key_find + 1 << "位!";
system("pause");
return 0;
}
- 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
文章来源: chuanchuan.blog.csdn.net,作者:川川菜鸟,版权归原作者所有,如需转载,请联系作者。
原文链接:chuanchuan.blog.csdn.net/article/details/118555087
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)