您的位置:首页 > 理论基础 > 数据结构算法

数据结构与算法学习之路:二分查找的非递归和递归算法

2014-11-11 20:55 555 查看
一、何为二分查找?

二分查找又称折半查找,优点是比较次数少,查找速度快,平均性能好;其缺点是要求待查表为有序表,且插入删除困难。因此,折半查找方法适用于不经常变动而查找频繁的有序列表。
二分查找的基本思想是:在有序序列中,通过与序列段中间的数作比较,减少多余的比较(例如key<mid,则在start和mid-1之间查找,反之在mid+1和end之间查找)

二、具体代码实现:

(本代码段并没有考虑溢出、low,high大小超出数据类型等等情况,有兴趣的读者可以自行搜索相关内容或者参考书籍了解)

#include <stdio.h>
#include <stdlib.h>

#define SUCESS 1
#define FALSE 0

#define MAXSIZE 10

int Binary_Search_Version1(int *test, int start, int end, int key);
int Binary_Search_Version2(int *test, int start, int end, int key);

int main(){
	int test[MAXSIZE] = { 1, 9, 22, 26, 34, 49, 52, 63, 78, 89 };
	int search;

	printf("请输入要查找地数:\t");
	scanf("%d", &search);

	if (Binary_Search_Version1(test, 0, MAXSIZE - 1, search))
		printf("\n找到了.\n");
	else
		printf("没找到\n");

	if (Binary_Search_Version2(test, 0, MAXSIZE - 1, search))
		printf("\n找到了.\n");
	else
		printf("没找到\n");
}

//递归算法
int Binary_Search_Version1(int *test, int start, int end, int key){
	int mid, low = start, high = end;

	if (low > high)
		return FALSE;
	mid = (low + high) / 2;
	if (key == test[mid])
		return SUCESS;
	else if (key < test[mid])
		Binary_Search_Version1(test, low, mid - 1, key);
	else
		Binary_Search_Version1(test, mid + 1, high, key);
}

//非递归算法
int Binary_Search_Version2(int *test, int start, int end, int key){
	int mid, low = start, high = end;

	while (low <= high){
		mid = (low + high) / 2;

		if (key == test[mid])
			return SUCESS;
		else if (key < test[mid]){
			high = --mid;
		}
		else
			start = ++mid;
	}
	return FALSE;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: