顺序查找与二分查找的算法实现

顺序查找的基本思想是:从表的一端开始,顺序扫描线性表,依次将扫描到的记录与给定值key比较,若相同,则扫描成功;若扫描结束后,仍然未找到与k相等的记录,则扫描失败。
#include "stdio.h"
#define MAX 10
int SeqSearch(int s[],int n,int key)
{
  int i;
  for(i=0;i<10&&s[i]!=key;i++);
  if(i>=10)
  return -1;
  else
  return i;
}
void main()
{
 int i,key;
 int a;
 int arry[MAX];
 printf("Input the data:");
 for(i=0;i<MAX;i++)
 {
   scanf("%d",&arry[i]);

 }
 printf("Input the key: ");
 scanf("%d",&key);
 a=SeqSearch(arry,10,key) ;
 printf("the key is %d it's position is %d.",key,a);
 getch();
}
运行结果如下所示:
Input the data:0 1 2 3 4 5 6 7 8 9
Input the key:9
the key is 9 it's position is 9.

二分查找的基本思想是:首先将给定的值key与表中中间位置的记录相比较,若二者相符,则查找成功;否则根据比较的结果确定下次查找的范围,然后在新的查找范围中进行查找,如此重复下去。
#include "stdio.h"
#define MAX 10
int BinSearch(int s[],int n,int key)
{
  int low=0;
  int high=n-1;
  int mid;
  while(low<high)
  {
    mid=(low+high)/2;
    if(s[mid]==key)
    return mid;
    if(s[mid]>key)
    high=mid-1;
    else
    low=mid+1;
  }
 return -1;
}
void main()
{
 int i,key;
 int a;
 int arry[MAX];
 printf("Input the data:");
 for(i=0;i<MAX;i++)
 {
   scanf("%d",&arry[i]);

 }
 printf("Input the key ");
 scanf("%d",&key);
 a=BinSearch(arry,10,key) ;
 printf("the key is %d it's position is %d:",key,a);
 getch();
}
运行结果如下所示:
Input the data:0 1 2 3 4 5 6 7 8 9
Input the key:5
the key is 5 it's position is 5.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值