posts - 63, comments - 37, trackbacks - 0, articles - 0
  IT博客 :: 首页 :: 新随笔 :: 联系 ::  :: 管理

顺序查找算法

Posted on 2006-06-13 14:15 Enjoy Life 阅读(3295) 评论(0)  编辑 收藏 引用 所属分类: DS study


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

#define MAX_LENGTH 100
typedef int KeyType;

typedef struct {
 KeyType *elem;
 int length; 
}SSTable; //顺序表的存储结构


/*
此算法比第二个算法多了一个判定i是否出界的流程,对于查找数目较少的情况,
二者查找时间相差不大,对于存在大量数据时,该算法的主要查找时间消耗再判
定是否出界上,所以第二个算法明显比第一个算法好,唯一增加的就是一个“哨兵”
数据。
int Search_Seq(SSTable ST, KeyType key){
 int i;
 for(i=1; i<=ST.length && ST.elem[i] != key; i++ )
  ;
 if(i<=ST.length)
  return i;
 else
  return 0;
}
*/

int Search_Seq(SSTable ST, KeyType key){
 int i;
 ST.elem[0] = key; //“哨兵”,如果顺序表中不存在要查找的数据的话,则查找指针必定指向该哨兵
 for(i = ST.length; ST.elem[i] != key; i--)
  ;
 return i;  //找到的话,则i != 0,否则i = 0
}


void main()
{
 int i, key;
 SSTable T;
 T.elem = (KeyType *)malloc(sizeof(KeyType));
 printf("How Many Entries Do You Want input\n");
 scanf("%d", &T.length);
 for(i=1; i<=T.length; i++){
  printf("Please input the %dth entries \n", i);
  scanf("%d", &T.elem[i]);
 }
 for (i=1; i<=T.length; i++)
  printf("%5d",T.elem[i]); //显示已经输入的所有数据
 printf("\nPlease input the data you want to search\n");
 scanf("%d", &key);
 i = Search_Seq(T,key);
 printf("the search data is locate the %dth(0 indicate can not find)\n",i); 
}

只有注册用户登录后才能发表评论。