顺序查找,二分查找, 递归查找
chechunli@chechunli-virtual-machine:tmp $ cat search.c
/* search */
#include
#include
#include
#define N 18
int a[N];
void show_array(int l, int r)
{
int i;
for(i = 0; i < N; ++i){
printf("%d ", a[i]);
}
}
int sequence_search(int l, int r, int n)
{
int i;
for(i = l; i < r ; ++i){
if(a[i] == n) return 1;
}
return 0;
}
int cycle_search(int l, int r, int n) //循环式2分查找
{
int m;
while(l<= r){
m = (l+r)/2;
if(n < a[m]) r = m-1;
else if (n > a[m]) l = m+1;
else return 1;
}
return 0;
}
int recurse_search(int l, int r, int n) //递归式2分查找
{
if(l > r) return 0;
int m = (l+r)/2;
if(n < a[m]) return recurse_search(l, m-1, n);
if(n > a[m]) return recurse_search(m+1, r, n);
return 1;
}
void swap(int i, int j)
{
int tmp;
tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
void bubble(int l, int r)
{
int i, j;
for(i = l; i < r; ++i){
for(j = r-1; j > 0; --j){
if(a[j] < a[j+1]){
swap(j, j+1);
}
}
}
}
int main(int argc, char *argv[])
{
int i;
srand(time(NULL));
for(i = 0; i < N; ++i){
a[i] = rand()%100;
}
show_array(0, N-1);
//printf("\n%d\n", recurse_search (0, N-1, 50));
//printf("\n%d\n", cycle_search (0, N-1, 50));
//printf("\n%d\n", sequence_search (0, N-1, 50));
return 0;
}
阅读(636) | 评论(0) | 转发(0) |