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

一、何为二分查找?

二分查找又称折半查找,优点是比较次数少,查找速度快,平均性能好;其缺点是要求待查表为有序表,且插入删除困难。因此,折半查找方法适用于不经常变动而查找频繁的有序列表。

二分查找的基本思想是:在有序序列中,通过与序列段中间的数作比较,减少多余的比较(例如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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值