二分查找 Binary Search

二分查找是一种在有序数组中高效搜索元素的算法,通过不断将搜索区间减半来定位目标值。时间复杂度为O(Log n)。本文介绍了二分查找的基本思想和递归实现方式。
摘要由CSDN通过智能技术生成

参考:Binary Search

Given a sorted array arr[] of n elements, write a function to search a given element x in arr[].

给定一个由n个元素组成的有序数组arr[],在arr[]中编写一个函数来搜索给定的元素x。

A simple approach is to do linear search.The time complexity of above algorithm is O(n). Another approach to perform the same task is using Binary Search.

 一个简单的方法是做线性搜索。上述算法的时间复杂度为O(n)。执行相同任务的另一种方法是使用二分查找。

Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise narrow it to the upper half. Repeatedly check until the value is found or the interval is empty.

通过将搜索间隔重复分成两半来搜索已排序的数组。从覆盖整个数组的区间开始。如果搜索键的值小于区间中间的项,则将区间缩小到下半部分。否则就缩小到上半部分。重复检查,直到找到值或间隔为空。

Example :

The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(Log n). 

//1, 递归写法   给定数组的low  和   high   int binarySearch(int arr[], int l, int r, int x) 

// Java implementation of recursive Binary Search 
class BinarySearch { 
	// Returns index of x if it is present in arr[l.. 
	// r], else return -1 
	int binarySearch(int arr[], int l, int r, int x) 
	{ 
		if (r >= l) { 
			int mid = l + (r - l) / 2; //l , r 为left ,right 

			// If the element is present at the 
			// middle itself 
			if (arr[mid] == x) 
				return mid; 

			// If element is smaller than mid, then 
			// it can only be present in left subarray 
			if (arr[mid] > x) 
				return binarySearch(arr, l, mid - 1, x); 

			// Else the element can only be present 
			// in right subarray 
			return binarySearch(arr, mid + 1, r, x); 
		} 

		// We reach here when element is not present 
		// in array 
		return -1; 
	} 

	// Driver method to test above 
	public static void main(String args[]) 
	{ 
		BinarySearch ob = new BinarySearch(); 
		int arr[] = { 2, 3, 4, 10, 40 }; 
		int n = arr.length; 
		int x = 10; 
		int result = ob.binarySearch(arr, 0, n - 1, x); 
		if (result == -1) 
			System.out.println("Element not present"); 
		else
			System.out.println("Element found at index " + result); 
	} 
} 
/* This code is contributed by Rajat Mishra */

// 2   没有给定的情况下,自己设定low =0; high=arrays.length-1;  

mid =low +(high-low)/2; 

参考:https://blog.csdn.net/nsjlive/article/details/87652925

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值