二分法查找:
#include<stdio.h>
typedef struct array{
int a[100];
}A,*ARR;
void set_value(ARR arr)
{
int i;
for(i = 0;i < 100;i++)
{
arr->a[i] = i;
}
}
void show_arr(struct array *arr)
{
int i;
for(i = 0;i < 100;i++)
{
printf("%d,",arr->a[i]);
}
printf("\n");
}
int Bsearch0(ARR arr,int target,int low,int high)
{
int m;
m = (low + high)/2;
if(m > target)
{
Bsearch0(arr,target,low,m-1);
}
else if(m < target)
{
Bsearch0(arr,target,m+1,high);
}
else
{
return arr->a[m];
}
}
int Bsearch1(ARR arr,int target,int low,int high)
{
int m;
while(low <= high)
{
m = (low+high)/2;
if(target > m)
{
low = m + 1;
}
else if(target < m)
{
high = m - 1;
}
else
{
return arr->a[m];
}
}
}
int main()
{
A arr1;
set_value(&arr1);
show_arr(&arr1);
printf("000:%d\n",Bsearch0(&arr1,55,0,99));
printf("111;%d\n",Bsearch1(&arr1,55,0,99));
return 0;
}
哈希查找:
#include<stdio.h>
int a[100];
int n;
int ShowArray(int *a,int n)
{
int i;
for(i=0;i<n;i++)
{
printf("%d,",a[i]);
}
printf("\n");
}
int main(void)
{
printf("input num:\n");
scanf("%d",&n);
int i,val;
for(i=0;i<n;i++)
{
scanf("%d",&val);
a[val%100] = val;
}
//建立一个简单的hash表
ShowArray(a,100);
printf("Search val:\n");
scanf("%d",&val);
//hash查找
if(a[val%100]==val)
{
printf("find pos:%d,val:%d\n",val%100,a[val%100]);
}
else
{
printf("not found\n");
}
return 0;
}
顺序查找:
#include<stdio.h>
int SqSearch(int *a,int n,int val) //顺序查找
{
int i;
for(i=0;i<n;i++)
{
if(a[i]==val)
{
printf("find pos:%d,val:%d\n",i,a[i]);
return 0;
}
}
printf("not found\n");
return -1;
}
int ShowArray(int *a,int n)
{
int i;
for(i=0;i<n;i++){
printf("%d,",a[i]);
}
printf("\n");
}
int main(void)
{
int a[5] = {1,4,6,9,3};
ShowArray(a,5);
SqSearch(a,5,22);
SqSearch(a,5,9);
return 0;
}