Search algorithm (1) -- binary search

Introduction: The binary search algorithm is an algorithm for finding an element in an ordered array, and the time complexity is Ο(logn)  .

 
1. Main steps
Sorted array arr (assuming small to large), the element to be searched for x
(1), start directly from the middle element, mid = (0+arr.length)/2
(2) If arr[mid] is greater than x, it means that the target index is on the left half of the mid index, and the left side is regarded as a complete array to continue searching
(3) If arr[mid] is less than x, it means that the target index is on the right half of the mid index, and the right side is regarded as a complete array to continue searching
(4), if arr[mid] is equal to x, then found
 
Second, the code implementation
public int search(int[] arr,int x) throws Exception{
	int start = 0;
	int end = arr.length-1;
	
	while(start<=end){
		int mid = (start+end)/2;
		
		if(arr[mid]>x){
			end = mid-1;
		}else if(arr[mid] == x){
			return mid;
		}else if(arr[mid]<x){
			start = mid+1;
		}
	}
	
	throw new Exception("not found"+x);
}
 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326232095&siteId=291194637