折半查找法
折半查找法:
只能针对有序数组进行查找。可以将数组利用选择或冒泡排序后再进行查找。
只能针对有序数组进行查找。可以将数组利用选择或冒泡排序后再进行查找。
#include<stdio.h>
#include<conio.h>
#define N 10
void xuanzhe(int a[],int n);
void maopao(int a[],int n);
void find(int a[],int n);
void main()
{
int a[N],i;
clrscr();
for(i=0;i<N;i++)
scanf("%d",&a[i]);
//xuanzhe(a,N);
maopao(a,N);
for(i=0;i<N;i++)
printf("%4d",a[i]);
printf("\n");
find(a,N);
}
void xuanzhe(int a[],int n)
{
int i,j,k,t;
for(i=0;i<n-1;i++)
{
k=i;
for(j=i+1;j<n;j++)
if(a[i]<a[j]) k=j;
if(k!=i)
{t=a[i];a[i]=a[k];a[k]=t;}
}
}
void maopao(int a[],int n)
{
int i,j,t,flag;
for(i=0;i<n-1;i++)
{
flag=0;
for(j=0;j<n-i-1;j++)
if(a[j]>a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
flag=1;
}
if(flag==0) break;
}
}
void find(int a[],int n)
{
int t,low,high,mid,found;
low=0;
high=n-1;
found=0;
printf("Input a number to be searched:");
scanf("%d",&t);
while(low<=high)
{
mid=(low+high)/2;
if(t==a[mid]) {found=1;break;}
else if(t>a[mid]) low=mid+1;
else high=mid-1;
}
if(found==1) printf("Found %d",t);
else printf("Not found %d",t);
}
#include<conio.h>
#define N 10
void xuanzhe(int a[],int n);
void maopao(int a[],int n);
void find(int a[],int n);
void main()
{
int a[N],i;
clrscr();
for(i=0;i<N;i++)
scanf("%d",&a[i]);
//xuanzhe(a,N);
maopao(a,N);
for(i=0;i<N;i++)
printf("%4d",a[i]);
printf("\n");
find(a,N);
}
void xuanzhe(int a[],int n)
{
int i,j,k,t;
for(i=0;i<n-1;i++)
{
k=i;
for(j=i+1;j<n;j++)
if(a[i]<a[j]) k=j;
if(k!=i)
{t=a[i];a[i]=a[k];a[k]=t;}
}
}
void maopao(int a[],int n)
{
int i,j,t,flag;
for(i=0;i<n-1;i++)
{
flag=0;
for(j=0;j<n-i-1;j++)
if(a[j]>a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
flag=1;
}
if(flag==0) break;
}
}
void find(int a[],int n)
{
int t,low,high,mid,found;
low=0;
high=n-1;
found=0;
printf("Input a number to be searched:");
scanf("%d",&t);
while(low<=high)
{
mid=(low+high)/2;
if(t==a[mid]) {found=1;break;}
else if(t>a[mid]) low=mid+1;
else high=mid-1;
}
if(found==1) printf("Found %d",t);
else printf("Not found %d",t);
}