码迷,mamicode.com
首页 > 其他好文 > 详细

查找 - 有序表查找

时间:2016-04-23 21:31:38      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:

#include<cstdio>
#include<cstdlib>
#include<cstring>

//折半查找
int Binary_Search(int *a,int n,int key){
	
	int cnt = 0; 
	
	int low,high,mid;
	low = 1;
	high = n;
	while(low <= high){
		cnt++;
		mid = (low + high) >> 1;	// 算术位运算
		if(key < a[mid]) high = mid - 1;
		else if(key > a[mid]) low = mid + 1;
		else {
			printf("共查找了 %d 次\n",cnt);
			return mid;
		}
	}
	return 0;
}

//插值查找
int Binary_Search2(int *a,int n,int key){
	
	int cnt = 0; 
	
	int low,high,mid;
	low = 1;
	high = n;
	while(low <= high){
		cnt++;
		mid = low + (high - low)*(key - a[low])/(a[high] - a[low]);
		if(key < a[mid]) high = mid - 1;
		else if(key > a[mid]) low = mid + 1;
		else {
			printf("共查找了 %d 次\n",cnt);
			return mid;
		}
	}
	return 0;
}

//斐波那契查找
int Fibonacci_Search(int *a,int n,int key){
	
	int cnt = 0; 
	
	int low,high,mid,i,k;
	int F[11] = {0,1,1,2,3,5,8,13,21,34,55};
	low = 1;
	high = n;
	k = 0;
	while(n>F[k]-1) k++;
	for(i=n;i<F[k]-1;i++) a[i] = a[n]; //将不满的数值补全
	while(low<=high){
		cnt++;
		mid = low + F[k-1]-1;
		if(key<a[mid]){
			high = mid-1;
			k = k -1;
		}else if(key>a[mid]){
			low = mid+1;
			k = k-2;
		}else{
			printf("共查找了 %d 次\n",cnt);
			if(mid<= n) return mid;
			else return n;
		}
	} 
	return 0;
} 


int main(){
	int a[11] = {0,1,16,24,35,47,59,62,73,88,99};
	printf("折半查找 59 的位置 %d\n\n",Binary_Search(a,10,59));
	printf("插值查找 59 的位置 %d\n\n",Binary_Search2(a,10,59));
	printf("斐波那契查找 59 的位置 %d\n\n",Fibonacci_Search(a,10,59));
	

	return 0;
} 

  

查找 - 有序表查找

标签:

原文地址:http://www.cnblogs.com/zhuozhuo/p/5425484.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!