Linear search of basic algorithm series

The linear search introduced in this article is a binary search method, and the prerequisite requires the array or sequence to be in order. Binary search is one of the more efficient search methods. The time complexity is logN, and the derivation process is relatively simple. Set the number of times to x, and N*(1/2)^x=1 (the reason is that it is equal to 1). In the worst case, there is only 1 element left at the end of the search); then x=logN, the base is 2. The code is as follows:

public int getIndex(int[]arr,int value){
    
    
	int min=0;
	int max=arr.length-1;
	int mid=(min+max)/2;
	while(true){
    
    
		if(min>max){
    
    
			return -1;
		}
		if(arr[mid]==value){
    
    
			return mid;
			break;
		}else{
    
    
			if(arr[mid]>value){
    
    
				max=mid-1;
				mid=(min+max)/2;
			}else if(arr[mid]<value){
    
    
				min=mid+1;
				mid=(min+max)/2;
			}
		}
	}
}
 

Guess you like

Origin blog.csdn.net/langxiaolin/article/details/113443801