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

一、何为二分查找?

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

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

    原文作者:查找算法
    原文地址: https://blog.csdn.net/u012403246/article/details/41017837
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞