SCAU-8621-数据结构-二分查找

本文介绍如何使用C语言实现静态顺序查找表的创建(Creat_Seq函数)和插入操作,同时利用递归二分搜索(Search_Bin)查找指定元素。通过malloc动态分配内存并演示了查找算法在查找过程中的应用。
摘要由CSDN通过智能技术生成
#include"malloc.h" /* malloc()等 */
#include"stdio.h"
#include"stdlib.h"

typedef int ElemType;
typedef struct /*静态查找表的顺序存储结构 */
{
	ElemType *elem; /* 数据元素存储空间基址,建表时按实际长度分配,0号单元留空 */
	int length; /* 表长度 */
}SSTable;
SSTable ST;
void Creat_Seq(SSTable &ST,int n)
{ /* 操作结果: 构造一个含n个数据元素的静态顺序查找表ST(数据来自数组r) */
	int i,temp;
	ST.elem=(ElemType *)malloc((n) * sizeof(ElemType)); /* 动态生成n个数据元素空间(0号单元不用) */
	if(!(ST).elem)
	{
		printf("ERROR\n");
		exit(0);
	} /*内存分配失败结束程序*/
	for(i=0;i<n;i++)
	{
		scanf("%d",&temp);
		*(ST.elem+i)=temp; /* 依次赋值给ST */
	}
	ST.length=n;
}

int Search_Bin(int i,int j,ElemType key)
{ /* 在顺序表ST中顺序查找其关键字等于key的数据元素。若找到,则函数值为 */
/* 该元素在表中的位置,否则为0。算法9.1 */
int k=(i+j)/2;
if((key>ST.elem[k]&&key<ST.elem[k+1])||(key>ST.elem[k-1]&&key<ST.elem[k])){
    return -1;
}
if(key<ST.elem[k]){
Search_Bin(i,k, key);
}

else if(key>ST.elem[k]){
    Search_Bin(k,j, key);
}
else {
    return k;
}
}

int main()
{
	int loc,key;
	int n;
	int i=ST.length/2;
	scanf("%d",&n);
	Creat_Seq(ST,n);
	scanf("%d",&key);
	loc = Search_Bin(0,ST.length,key);
	if(loc!=-1)
		printf("The element position is %d.",loc);
	else
		printf("The element is not exist.");
		return 0;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值