二分查找 迭代方法与递归方法——java实现

本文介绍了一种高效的查找数组元素的方法——二分查找算法,并通过Java实现递归和非递归两种方式。该算法的前提是数组必须有序,其时间复杂度为O(log2n),相较于线性查找更高效。

    相比较于线性查找,二分查找算法是查找数组中元素的高效方法,它生成一棵二分查找树,复杂度为O(log2n)。

当然前提是数组有序。

import java.util.Scanner;

public class BinarySearch {
	
	public static int binarySearch(int[] arr, int purpose) {
		int bottom = 0;
		int top = arr.length - 1;
		while (bottom <= top) {
			int mid = (bottom + top) / 2;
			if (arr[mid] == purpose)
				return mid;
			else if (arr[mid] > purpose)
				top = mid - 1;
			else
				bottom = mid + 1;
		}
		return -1;
	}
	
	public static int recursiveBinarySearch(int[] arr, int purpose, int bottom ,int top) {
		
		if (bottom > top)
			return -1;
		int mid = (bottom + top) / 2;
		if (arr[mid] == purpose)
				return mid;
	    return arr[mid] > purpose ? recursiveBinarySearch(arr, purpose, bottom, mid - 1) :
			recursiveBinarySearch(arr, purpose, mid + 1, top);
	}
	
	public static void main(String[] args) {
		int[] arr = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
		Scanner input = new Scanner(System.in);
		System.out.print("Enter the number you want to find: ");
		int num = input.nextInt();
		
		int index = recursiveBinarySearch(arr, num, 0, arr.length - 1);
		if (index == -1) {
			System.out.println("Sorry ! it's NOT FOUND");
			System.exit(0);
		}
		System.out.printf("Find! It's index is %d\n", index);
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值