二分查找之递归与非递归实现

package algorithm;

/**
 * 
 * @Description 二分查找的递归和非递归的实现
 * @author ningqian QQ:2587658527
 * @version
 * @date 2021年3月18日下午7:28:17
 */
public class BinarySearch {
    
    
	public static void main(String[] args) {
    
    
		int[] arr = {
    
    1,1,3,8,8,10,11,67,100,100};
		BinarySearch search1 = new BinarySearch();
		//search1.binarySearchRecursion(arr, 0, arr.length-1, 8);
		search1.binarySearchNoRecursion(arr,8);
		
	}
	//二分查找的递归实现方法
	public void binarySearchRecursion(int[] arr,int left,int right,int key) {
    
    
		int l = left;
		int r = right;
		int mid = (l+r)/2;
		if(l<=r) {
    
    
			
			if(key<arr[mid]) {
    
      //向左半部分
				binarySearchRecursion(arr, left, mid-1, key);
			}
			else if(key>arr[mid]){
    
      //向右半部分查找
				binarySearchRecursion(arr,mid+1,right,key);
			}
			else {
    
    
				System.out.println("找到了,位置 "+mid);  //找到第一个key
				int toLeft = mid-1;
				int toRight = mid+1;
				while(toLeft>=0&&arr[toLeft]==key) {
    
     //向左瞅瞅还有没有一样的
					System.out.println("又找到了,位置 "+(toLeft));
					toLeft-=1;
				}
				while(((toRight)<=arr.length-1)&&arr[toRight]==key) {
    
     //向右瞅瞅还有没有一样的
					System.out.println("又找到了,位置 "+(toRight));
					toRight+=1;
				}
				return;
			}
		}
		else {
    
    
			System.out.println("没找到");
		}
	}
	//二分查找的非递归实现
	public void binarySearchNoRecursion(int[] arr,int key) {
    
    
		int left = 0;
		int right = arr.length-1;
		while(left<=right) {
    
    
			int mid = (left+right)/2;
			if(arr[mid]==key) {
    
    
				System.out.println("找到了! 位置 "+mid);
				int toLeft = mid-1;
				int toRight = mid+1;
				while(toLeft>=0&&arr[toLeft]==key) {
    
    
					System.out.println("又找到了,位置 "+(toLeft));
					toLeft-=1;
				}
				while(((toRight)<=arr.length-1)&&arr[toRight]==key) {
    
    
					System.out.println("又找到了,位置 "+(toRight));
					toRight+=1;
				}
				return;
			}
			else if(key<arr[mid]) {
    
    
				right = mid-1;
			}
			else {
    
    
				left = mid+1;
			}
		}
		System.out.println("没找到!");
		
		
		
		
	}

}

猜你喜欢

转载自blog.csdn.net/m0_38143506/article/details/114989526
今日推荐