h)"/> h)"/>

坐等解释折半查找法问题

坐等解释折半查找法问题

先贴个正确的:

#include "stdio.h"

int i,n,l,h,x,d;

int binsearch(int a[],int l,int h,int x)

{

int m;

if(l>h)

return (-1);

else

{

m=(l+h)/2;

if(x<a[m])

return (binsearch(a,l,m-1,x));

else if(x==a[m])

return m;

else

return (binsearch(a,m+1,h,x));

}

}

main()

{

int b[]={2,3,1,4,5,6,7,95,84,27};

printf("已初始化了一个数组,元素值如下:\n");

for(i=0;i<10;i++)

printf("%3d",b[i]);

printf("\n");

printf("请输入您需要查找的关键字n:\n");

scanf("%d",&d);

n=binsearch(b,0,9,d);

if(n>=0)

{

printf("查找的结果如下:\n");

printf("b[%d]=%d",n,d);

}

else

printf("未找到\n");

}

楼主代码修改:

#include<stdio.h>

#include "stdlib.h"

void printarray(int a[],int n)//打印数组

{

int i;

for(i=0;i<n;i++)

{

printf("%2d ",a[i]);

}

}

void bubblesort(int a[],int n)//数组冒泡排序,输入的数据并非都是有序的

{

int i,j,temp=0;

for(i=0;i<n;i++)

{

for(j=n-1;j>i;j--)

{

if(a[j]<a[j-1])

{

temp=a[j];

a[j]=a[j-1];

a[j-1]=temp;

}

}

}

}

int main()

{

int i,l=15,n=0,m,x,a[15]={80,75,92,61,65,71,59,63,70,85,87,90,76,77,85};

bubblesort(a,15);

printarray(a,15);

printf("\n请输入要检测的数\n");

scanf("%d",&x);

while(n<=l) //查找区间的低下标不超过高下标

{

m=(l+n)/2;//取数组的中间元素

if (x==a[m])break;

else

{

if (x>a[m])

n=m+1;

if (x<a[m])

l=m-1;

}

}

if (l>0&&n<15)

printf("第%d个位置:\n",m);

else

printf("无此数\n");

system("pause");

}

首页