L是用户传入的一个线性表。函数BinarySearch要查找X在Data中的位置,即数组下标(注意:元素从下标1开始存储)。找到则返回下标,否则返回一个特殊的失败标记NotFound。
题目参考自:https://pintia.cn/problem-sets/434/problems/965458856133562368
以下解答仅供参考
二分查找也称折半查找(Binary Search),它是一种效率较高的查找方法。但是,折半查找要求线性表必须采用顺序存储结构,而且表中元素按关键字有序排列。
代码实现
#include <stdio.h>
#include <stdlib.h>
#include<malloc.h>
#include<time.h>
#define MAXSIZE 10
#define NotFound 0
typedef struct LNode {
int Data[MAXSIZE];
int Last; /* 保存线性表中最后一个元素的位置 */
}Node;
Node* ReadInput(); //顺序表的初始化
void SortList(Node *l);//对顺序表进行排序
void printfList(Node *l);//遍历顺序表
int BinarySearch(Node *l, int x);//二分查找算法
int main()
{
Node *L;
int X;
int P;
L = ReadInput();
printf("排序后的顺序表为:\n");
printfList(L);
printf("输入需要查找的元素:");
scanf("%d", &X);
P = BinarySearch(L, X);
printf("%d的下标为:%d\n",X ,P);
return 0;
}
Node* ReadInput() {
Node *l = (Node *)malloc(sizeof(Node));
printf("输入数组的长度:");
int len;
scanf("%d", &len);
if (len>MAXSIZE|| l == NULL)
{
return NULL;
}
srand((int)time(0));
l->Last = 0;
for (int i = 0; i < len; i++)
{
l->Data[i] = rand() % 100 + 1;
l->Last++;//确保last存储的是最后一个元素
}
SortList(l);
return l;
}
void SortList(Node *l) {
//冒泡法对顺序表进行递增排序
int temp;
for (int i = 0; i <l->Last-1; i++)
{
for (int j = i; j < l->Last; j++)
{
if (l->Data[i]>l->Data[j])
{
temp = l->Data[j];
l->Data[j] = l->Data[i];
l->Data[i] = temp;
}
}
}
}
void printfList(Node *l) {
int i = 1;
while (i<=l->Last)
{
printf("%d ", l->Data[i - 1]);
i++;
}
printf("\n");
}
/**
1、找到顺序表的第一个下标和最后一个下标
2、借用循环---终止条件为:begin>end
3、在循环中求出顺序表的中间元素
4、将中间元素和目标值作比较
5、相等直接返回中间值的下标+1,目标值大于中间值,则将第一个元素的下标改为:mid+1,否则最后一个元素的下标改为mid-1
*/
int BinarySearch(Node *l, int x) {
int begin = 0;
int end = l->Last-1;
int mid = 0;
if (end<begin)
{
return NotFound;//判断顺序表是否为空
}
while (begin<=end)
{
mid = begin + ((end - begin) / 2);
if (l->Data[mid]==x)
{
return mid+1;//相等就返回对应下标+1
}
else if (l->Data[mid]>x)
{
end = mid - 1;//小于就end = mid-1
}
else {
begin = mid + 1;//大于就begin的值变化
}
}
return NotFound;
}