提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
C++实现一个数组的的二分查找
一、LNode数据结构
该数据结构中包括数据的最大容量以及线性表中的最后一个位置,代码如下(示例):
struct LNode
{
ElementType Data[MAXSIZE];
Position Last; /* 保存线性表中最后一个元素的位置 */
};
typedef struct LNode* List;
二、ReadInput()函数
对LNode定义的对象进行初始化代码如下(示例):
void ReadInput(List L)
{
scanf("%d", &L->Last);
for (int i = 0; i < L->Last; i++)
{
scanf("%d", L->Data + i);
}
}
三、BinarySearch()二分查找函数
该函数的输入为List指针和所需要查找的数字X,List指向的对象包含需要进行查找的数组和最后一个数据的位置。返回值为查找的数字X在数组中的位置,从1开始计算,若查找不到,则返回Not Found(0)。
代码的中心思想为二分查找,二分查找有左右两个端点,分别设为l点和r点,l的初始值为0,r的初始值为L->Last,也就是待查找数组有效数据的长度,注意(L->Last)是取不到的。即
Poistion l = 0;
Poistion r = L->Last;
再根据二分查找,取中间值mid = (l+r)/2,其中心思想如下:
Position mid = (l + r) >> 1;//右移运算符
if (Li->Data[mid] == X)
return mid + 1;
if (Li->Data[mid] < X)
l = mid + 1;
else r = mid;
四、全部程序
#include <iostream>
#include <cmath>
#define MAXSIZE 10//数组的最大值,可以根据需要修改
#define NotFound 0//未找到
typedef int ElementType;//数组里面元素的类型
typedef int Position;//元素的位置的类型表示
struct LNode {
ElementType Data[MAXSIZE];
Position Last; /* 保存线性表中最后一个元素的位置 */
};
typedef LNode* List;
void ReadInput(List L)
{
scanf("%d", &L->Last);
for (int i = 0; i < L->Last; i++)
{
scanf("%d", L->Data + i);
}
}/* 裁判实现,细节不表。元素从下标1开始存储 */
Position BinarySearch(LNode* Li, ElementType X)
{
Position l = 0, r = Li->Last;
while (l < r) {
Position mid = (l + r) >> 1;//右移运算符
if (Li->Data[mid] == X)
{
return mid + 1;
}
if (Li->Data[mid] < X)
{
l = mid + 1;
}
else r = mid;
}
return NotFound;
}
int main()
{
ElementType X = 50;
Position P1;
Position P2;
Position P3;
List L = (LNode*)malloc(sizeof(LNode));
List L1 = new LNode();
ReadInput(L);
//ReadInput(L1);
scanf("%d", &X);
P1 = BinarySearch(L, X);
//P2 = BinarySearch(L1, X);
printf("%d\n", P1);
return 0;
}