#include<stdio.h>
int main()
{
int x;
printf("Please enter the array length:\n");
scanf("%d",&x);
int a[x],i,j,t;
printf("Please enter the integer of the corresponding array:\n");
for(i=0;i<x;i++)
{
scanf("%d",&a[i]);
}
printf(" \n");
for(j=0;j<x-1;j++)//遍历法排序
{
for(i=j+1;i<x;i++)
{
if(a[j]>a[i])
{
t=a[j];
a[j]=a[i];
a[i]=t;
}
}
}
printf("The sorted number:\n");
for(i=0;i<x;i++)
{
printf("%d",a[i]);
printf(" ");
}
int query;
printf("\nPlease enter the number to query:\n");//折半查找
scanf("%d",&query);
int left,mid,right;
left=0;
right=sizeof(a)/sizeof(a[0]);
while(left<=right)
{
mid=(left+right)/2;
if(a[mid]>x)
{
right=mid-1;
}
else if(a[mid]<x)
{
left=mid+1;
}
else break;
}
if(left<=right)
{
printf("The number is in the array!\n\n");
}
else if(left>right)
{
printf("Without this number!\n\n");
}
return 0;
}
遍历法排序和折半查找
最新推荐文章于 2024-07-01 15:10:19 发布