0
点赞
收藏
分享

微信扫一扫

大学数据结构实验(六.查找算法的应用一)


大学程序实验.数据结构.查找算法的应用一.顺序查找和折半查找

  • ​​0 目录​​
  • ​​6 查找算法的应用​​
  • ​​6.1 顺序查找和折半查找​​
  • ​​6.1.1 题目​​
  • ​​6.1.2 源码​​
  • ​​1.1.3 下载​​

  • ​​2 下一章​​

0 目录

6 查找算法的应用

6.1 顺序查找和折半查找

6.1.1 题目

1、 编写顺序查找的算法,如果查找成功打印出位置和比较次数,如果查找失败,则打印查找失败信息。
2、 编写折半查找的算法,如果查找成功打印出位置和比较次数,如果查找失败,则打印查找失败信息.

6.1.2 源码

// 顺序查找.cpp : Defines the entry point for the console application.
//

#include "stdio.h"
#include "stdlib.h"

#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define MAXSIZE 50

typedef int Status;
typedef int ElemType;

typedef struct
{
ElemType data[MAXSIZE];
ElemType length;
}SqList;


Status ListCreate(SqList *&L)
{
int i;
int value;

L=(SqList*)malloc(sizeof(SqList));
L->length=0;

printf("---<顺序表的创建>---\n");
printf("请输入顺序表的元素数:");
label:
scanf("%d",&value);

if(value>0&&value<MAXSIZE)
{
printf("\n");
printf("请输入%d个数据:\n",value);

for(i=1;i<=value;i++,L->length++)
{
printf("第%d个元素:",i);
scanf("%d",&L->data[i]);
}
}
else
{
printf("\n");
printf("输入的数值不合法或超出!\n");
printf("请重新输入:");
goto label;
}

return OK;
}

Status Sequential_Search(int *a,int n,int key)
{
int i;

a[0]=key;
i=n;
while(a[i]!=key)
{
i--;
}
return i;
}


Status Binary_Search(int *a,int value,int key,int *count)
{
int low,high,mid;
int num=0;

low=1;
high=value;

while(low<=high)
{
mid=(low+high)/2;
if(key<a[mid])
{
high=mid-1;
}
else if(key>a[mid])
{
low=mid+1;
}
else
{
num++;
*count=num;
return mid;
}
num++;
}

return 0;
}

Status SqListMenu()
{
int value;

printf("\n");
printf(" ___>>顺序表查找<<___\n");
printf("| |\n");
printf("| 1.顺序查找 |\n");
printf("| 2.折半查找 |\n");
printf("| 3.退出 |\n");
printf("|____________________|\n");


printf("请你要选择的查找操作:");
label:
scanf("%d",&value);

if(value>0&&value<4)
{
return value;
}
else
{
printf("你输入的操作有误,请重新输入:");
goto label;
}
}


Status main()
{
SqList *L;
int value;
int a,*p;
p=&a;
int key;
int RET;

ListCreate(L);
label:
printf("\n");
printf("请输入你要查找的数:");
scanf("%d",&key);

value=SqListMenu();

if(value==1)
{
RET=Sequential_Search(L->data,L->length,key);

if(RET!=NULL)
{
printf("\n");
printf("%d是第%d个元素\n",key,RET);
printf("比较次数为:%d\n",L->length-RET+1);
}
else
{
printf("\n");
printf("无此元素!\n");

}

goto label;
}
else if(value==2)
{
RET=Binary_Search(L->data,L->length,key,p);

if(RET!=NULL)
{
printf("\n");
printf("%d是第%d个元素\n",key,RET);
printf("比较次数为:%d\n",*p);

}
else
{
printf("\n");
printf("无此元素!\n");
}

goto label;
}
else if(value==3)
{
printf("\n");
printf("退出!\n");
}
else
{
printf("请输入正确的操作!\n");
goto label;
}

return OK;
}

1.1.3 下载

链接地址: ​​6.1_顺序查找.CPP​​


举报

相关推荐

0 条评论