• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Crazy丶
享受现在的每一天........
博客园    首页    新随笔    联系   管理    订阅  订阅

折半查找

数据结构 折半查找

#include<stdio.h>
#include<stdlib.h>
typedef int Status;
Status binSearch(int *p,int key,int low,int high)
{
int middle;
while(low<=high)
{
middle=(low+high)/2;
if(p[middle]>key)
{
high=middle-1;
}
else if(p[middle]<key)
{
low=middle+1;
}
else
{
return middle;
}
}
return 0;
}
void printArray(int *p,int m)
{
int i;
for(i=0;i<m;i++)
printf("%d\n",*(p+i));
}
void bubbleSort(int *p,int m)
{
int i,j;
for(i=1;i<m;i++)
for(j=0;j<m-i;j++)
{
if(p[j]>p[j+1])
{
int tem;
tem=p[j];
p[j]=p[j+1];
p[j+1]=tem;
}

}
}
int main()
{
int m,i,key,ret;
printf("Please input the array size:");
scanf("%d",&m);
int *p=(int *)malloc(m*sizeof(int));
printf("输入a[0]-a[%d]:\n",m-1);
for(i=0;i<m;i++)
scanf("%d",p+i);
printf("\n");
printf("排序前:\n");
printArray(p,m);
printf("排序后:\n");
bubbleSort(p,m);
printArray(p,m);
printf("please input the number value which you want to search:\n");
scanf("%d",&key);
ret=binSearch(p,key,0,m-1);
if(ret)
{
printf("The number %d is in %d position\n",key,ret+1);
}
else
{
printf("The number %d is not exist\n");
}
free(p);
return 0;
}

posted @ 2015-06-06 09:53  Crazy丶  阅读(138)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3