数据结构 查找

#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
 

#define  KEYTYPE    int  
#define  MAXSIZE    100  
typedef  struct
{  KEYTYPE  key;
 }SSELEMENT;

typedef  struct
{  SSELEMENT  r[MAXSIZE];   
 int   len;
}SSTABLE;


 
int seq_search(KEYTYPE k,  SSTABLE  st)
{/*表上顺序查找元素*/  
    st.r[0].key=k;
    int i=st.len;
    while(st.r[i].key!=k)
    {i--;}
    return i;
}

int bin_search(KEYTYPE k,  SSTABLE  st)
{/*表上折半查找元素*/  
    int low=1,high=st.len,mid=0;
    while(low<=high)
    {
        mid=(low+high)/2;
        if(st.r[mid].key>k)
        {
            high=mid-1;
        }
        else if(st.r[mid].key<k)
        {
            low=mid+1;
        }
        else
            return mid;
    }
            return 0;

}





int main( )
{
SSTABLE  a;   int  i, j, k;
/*printf("请输入顺序表元素(整型量),用空格分开,-99为结束标志 :"); */
 printf("please input the int elements and separate by space. -99 is the end\n ");
j = 0;  k = 1;  i = 0;
scanf("%d",&i);
while (i != -99)  
{ j++;  
a.r[k].key = i;
 k++;  
scanf("%d",&i);
}/*输入顺序表元素*/
a.len = j;


/*printf("\n顺序表元素列表显示 :"); */
printf("the elements are:");
for (i = 1; i<=a.len; i++)
printf("%d ",a.r[i].key); printf("\n");

/*printf("\n输入待查元素关键字 : "); */
printf("please input the key that you want to find:");
scanf("%d",&i);
k = seq_search(i, a);
if (k == 0)
/*printf("表中待查元素不存在\n\n"); */
printf("there is not the element\n");
else
printf("the element is at %d\n",k );

printf("please input the key that you want to find:");
scanf("%d",&i);
k=bin_search(i, a);
if (k == 0)
/*printf("表中待查元素不存在\n\n"); */
printf("there is not the element");
else
printf("the element is at %d\n",k );
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值