折半查找

本文介绍了一种常用的搜索算法——二分查找,并通过递归和非递归两种方式实现了该算法。文章首先让用户输入一系列整数并按顺序排列,然后输入要查找的目标值,最后展示查找结果。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;
int n,rec[100],Key;
void Binary_search(int Key)
{
	int mid,low,high,find;
	low = 0;high = n-1;find = 0;
	while (!find && low <= high)
	{
		mid = (low + high) / 2;
		if (Key == rec[mid])
		{
			printf("Successfully searched! The index is:%d\n", mid);
			find = 1;
		}
		else if (Key < rec[mid]) high = mid - 1;
		else low = mid + 1;
	}
	if (find == 0) printf("Search Failed!\n");
}
int Binary_search1(int K, int low, int high)
{
    if (low > high) return -1;
    int mid = (low + high) / 2;
    if (K == rec[mid]) return mid;
    else if (K < rec[mid]) return Binary_search1(K, low,mid-1);
    else return Binary_search1(K,mid+1,high);
}
int main()
{
	printf("Please input the number N of records(integers)\n");
	printf("N = ");
	scanf("%d", &n);
	printf("Please input N records\n");
	for (int i=0;i<n;i++)
		scanf("%d", &rec[i]);
	printf("Please input the key you want to find\n");
	printf("Key = ");
	scanf("%d", &Key);
	
	
	printf("Recursive Method:\n");
	Binary_search(Key);
	
	
	printf("Non-recursive Method:\n");
	int result = Binary_search1(Key,0,n-1);
	if (result == -1)
         printf("Search Failed!\n");
    else
        printf("Successfully searched! The index is:%d\n", result);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值