#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
",*(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]:
",m-1);
for(i=0;i<m;i++)
scanf("%d",p+i);
printf("
");
printf("排序前:
");
printArray(p,m);
printf("排序后:
");
bubbleSort(p,m);
printArray(p,m);
printf("please input the number value which you want to search:
");
scanf("%d",&key);
ret=binSearch(p,key,0,m-1);
if(ret)
{
printf("The number %d is in %d position
",key,ret+1);
}
else
{
printf("The number %d is not exist
");
}
free(p);
return 0;
}