查找

来源:互联网 发布:淘宝低于5元不计销量 编辑:程序博客网 时间:2024/04/30 20:47

顺序查找:

#include <stdio.h>
#include <stdlib.h>
typedef int InfoType;

#define n 10      //¼ÙÉèµÄÎļþ³¤¶È
typedef int KeyType;    //¼ÙÉèµÄ¹Ø¼ü×ÖÀàÐÍ
typedef struct{      //¼Ç¼ÀàÐÍ
 KeyType key;     //¹Ø¼ü×ÖÏî
 InfoType otherinfo;    //ÆäËüÊý¾ÝÏ´ËÀàÐÍÒÀÀµÓÚÓ¦ÓÃ
}NodeType;
typedef NodeType SeqList[n+1];  //0ºÅµ¥ÔªÓÃ×÷ÉÚ±ø


void main()
{
 int SeqSearch(SeqList R,KeyType K);
 void PrintList(SeqList L);
 SeqList L;
 int i,x;
 for (i=1;i<=n;i++)
  L[i].key=rand()%100;
 PrintList(L);   //´òӡ˳Ðò±í
 printf("ÊäÈëÒª²éÕÒµÄÖµ£º");
 scanf("%d",&x);
 i=SeqSearch(L,x);  //˳Ðò±í²éÕÒ
 if (i==0)
  printf("δÕÒµ½%d!\n",x);
 else
  printf("ÕÒµ½%d£¬ÔÚµÚ%d¸öλÖÃÉÏ!\n",x,i);
}

//˳Ðò±íµÄ´òÓ¡£º
void PrintList(SeqList L)
{ int i;
 for (i=1;i<=n;i++)
  printf("%d  ",L[i].key);
 printf("\n");
}

int SeqSearch(SeqList R,KeyType K)
{ //ÔÚ˳Ðò±íR[1..n]ÖÐ˳Ðò²éÕҹؼü×ÖΪKµÄ½áµã£¬
  //³É¹¦Ê±·µ»ØÕÒµ½µÄ½áµãλÖã¬Ê§°Üʱ·µ»Ø0
 int i;
 R[0].key=K;      //ÉèÖÃÉÚ±ø
 for(i=n;R[i].key!=K;i--);  //´Ó±íºóÍùÇ°ÕÒ
 return i;
}

 

折半查找 :

#include <stdio.h>
#include <stdlib.h>
typedef int InfoType;

#define n 10      //¼ÙÉèµÄÎļþ³¤¶È
typedef int KeyType;    //¼ÙÉèµÄ¹Ø¼ü×ÖÀàÐÍ
typedef struct{      //¼Ç¼ÀàÐÍ
 KeyType key;     //¹Ø¼ü×ÖÏî
 InfoType otherinfo;    //ÆäËüÊý¾ÝÏ´ËÀàÐÍÒÀÀµÓÚÓ¦ÓÃ
}NodeType;
typedef NodeType SeqList[n+1];  //0ºÅµ¥ÔªÓÃ×÷ÉÚ±ø


void main()
{
 int SeqSearch(SeqList R,KeyType K);
 void PrintList(SeqList L);
 SeqList L;
 int i,x;
 for (i=1;i<=n;i++)
  L[i].key=rand()%100;
 PrintList(L);   //´òӡ˳Ðò±í
 printf("ÊäÈëÒª²éÕÒµÄÖµ£º");
 scanf("%d",&x);
 i=SeqSearch(L,x);  //˳Ðò±í²éÕÒ
 if (i==0)
  printf("δÕÒµ½%d!\n",x);
 else
  printf("ÕÒµ½%d£¬ÔÚµÚ%d¸öλÖÃÉÏ!\n",x,i);
}

//˳Ðò±íµÄ´òÓ¡£º
void PrintList(SeqList L)
{ int i;
 for (i=1;i<=n;i++)
  printf("%d  ",L[i].key);
 printf("\n");
}

int SeqSearch(SeqList R,KeyType K)
{ //ÔÚ˳Ðò±íR[1..n]ÖÐ˳Ðò²éÕҹؼü×ÖΪKµÄ½áµã£¬
  //³É¹¦Ê±·µ»ØÕÒµ½µÄ½áµãλÖã¬Ê§°Üʱ·µ»Ø0
 int i;
 R[0].key=K;      //ÉèÖÃÉÚ±ø
 for(i=n;R[i].key!=K;i--);  //´Ó±íºóÍùÇ°ÕÒ
 return i;
}

 

原创粉丝点击