数据结构 查找

时间:2021-01-21 14:43:56
#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;
}