#include "stdio.h"
int main()
{
int a[10],right=0,left=9,n,mid;
printf("Please input an arrylist from max to min:");
for(int i=0;i<10;i++)
scanf("%d",&a[i]);
printf("Please input what number you wanna search:");
scanf("%d",&n);
while(right<=left)
{
mid=(right+left)/2;
if(a[mid]<n)
left=--mid;
else if(a[mid]>n)
right=++mid;
else
{
printf("number has been found in the arrylist!");
break;
}
}
if(right>left)
printf("The number isn't in the arrylist!");
}
改进版本(函数递归版)
#include "stdio.h"
int midsearch(int arr[],int n)
{
int mid,right,left=0;
right=sizeof(arr)/4-1; //用sizeof来计算数组的字节通过计算得到最后一个元素标记
mid=(right+left)/2;
if(arr[mid]<n)
left=++mid;
else if(arr[mid]>n)
right=--mid;
else if(arr[mid]==n)
return 1;
if(left<right)
return midsearch(arr,n); //如果没有查找到数据就进行递归
else
return -1; //下面为穷尽数据时的出口
}
int main()
{
int a[10],n;
printf("Please input an arrylist from min to max:");
for(int i=0;i<10;i++)
scanf("%d",&a[i]);
printf("Please input what number you wanna search:");
scanf("%d",&n);
if(midsearch(a,n)<0)
printf(">.<The number isn't in the arrylist");
else
printf("^.^The nubmer has been found in the arrylist!");
}
版权声明:本文为Saras1原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。