Search algorithm --- binary search (recursive method)

Binary search

Prerequisites

Our binary search must be search in an ordered array

Whether it’s from small to large or from large to small

topic

Please perform a binary search {1, 8,10,89,1000,1234} on an ordered array , enter a number to
see if the array is in this number, and give the subscript, if not, it will prompt that there is no such number".

Ideas

We will use recursive thinking in our binary search this time. Of course, there are also non-recursive methods. I will learn separately.

1. First determine the middle subscript of the array mid mid = (left+ right)/2

2. Compare findValue with our arr[mid]

​ If findValue>arr[mid], find it recursively to the right

​ If findValue<arr[mid], search recursively to the left

​ If you happen to find it, return

What is our recursive exit (end condition)

1. Found it, go back and exit

2. When recursing the entire array, findValue is not found, and we need to end the recursion, when our left>right means it is over

Code

//二分查找
//@author 王
public class BinarySearch {
    
    

	public static void main(String[] args) {
    
    
		// TODO Auto-generated method stub
		int arr[] = {
    
    1,8,10,89,1000,1234};//必须是有序数组
		int resultIndex = binarySearch(arr, 0, arr.length -1, 1234);
		System.out.println(resultIndex);
	}
	/**
	 * 
	 * @param arr			数组
	 * @param left			左边索引
	 * @param right			右边索引
	 * @param findValue		需要找的数字,找到返回下标,未找到返回-1
	 * @return
	 */
	//二分查找算法
	public static int binarySearch(int[] arr,int left,int right,int findValue) {
    
    
		int mid = (left+right)/2;
		int midValue = arr[mid];
		
		if(findValue >midValue){
    
    
			//向右递归
			return binarySearch(arr, mid+1, right, findValue);
		}else if(findValue < midValue){
    
    
			//向左递归
			return binarySearch(arr, left, mid-1, findValue);
		}else{
    
    
			return mid;
		}
	}

}

It is easy for us to find the problem. There is a problem with our recursion. If we find a non-existent data rescue, an error will be reported. This error is caused by dead recursion.

Exception in thread "main" java.lang.StackOverflowError
	at 查找算法.BinarySearch.binarySearch(BinarySearch.java:27)

Then we have to write this recursive end exit

Improve

//二分查找
//@author 王
public class BinarySearch {
    
    

	public static void main(String[] args) {
    
    
		// TODO Auto-generated method stub
		int arr[] = {
    
    1,8,10,89,1000,1234};//必须是有序数组
		int resultIndex = binarySearch(arr, 0, arr.length -1, 123);
		if(resultIndex != -1){
    
    
			System.out.println(resultIndex);
		}else{
    
    
			System.out.println("没有找到这个数字");
		}
	}
	/**
	 * 
	 * @param arr			数组
	 * @param left			左边索引
	 * @param right			右边索引
	 * @param findValue		需要找的数字,找到返回下标,未找到返回-1
	 * @return
	 */
	//二分查找算法
	public static int binarySearch(int[] arr,int left,int right,int findValue) {
    
    
		if(left > right){
    
    
			return -1;
		}
		int mid = (left+right)/2;
		int midValue = arr[mid];
		if(findValue >midValue){
    
    
			//向右递归
			return binarySearch(arr, mid+1, right, findValue);
		}else if(findValue < midValue){
    
    
			//向左递归
			return binarySearch(arr, left, mid-1, findValue);
		}else{
    
    
			return mid;
		}
	}

}

Let's expand it a bit, which is also the teacher’s after-school exercise
{1,8,10,89,1000,1000,1000,1234} When there are multiple identical values ​​in an ordered array, how to find all the values To, for example, 1000 here.

The idea is similar to what I learned last time, we can use a collection to store our index value and return to our collection

Code

public class BinarySearch {
    
    

	public static void main(String[] args) {
    
    
		// TODO Auto-generated method stub
		int arr[] = {
    
    1,8,10,89,1000,1000,1000,1234};//必须是有序数组
		ArrayList<Integer> resultIndex = binarySearch2(arr, 0, arr.length -1, 1000);
		if(resultIndex.size() == 0){
    
    
			System.out.println("没有找到这个数字");
		}else{
    
    
			System.out.println(resultIndex);
		}
	}
    public static ArrayList<Integer> binarySearch2(int[] arr,int left,int right,int findValue) {
    
    
			if(left > right){
    
    
				return new ArrayList<Integer>();
			}
			int mid = (left+right)/2;
			int midValue = arr[mid];
			if(findValue >midValue){
    
    
				//向右递归
				return binarySearch2(arr, mid+1, right, findValue);
			}else if(findValue < midValue){
    
    
				//向左递归
				return binarySearch2(arr, left, mid-1, findValue);
			}else{
    
    
				ArrayList<Integer> list = new ArrayList<Integer>();
				int temp = mid -1;
				//向左边扫描
				while(true){
    
    
					if(temp < 0 || arr[temp] != findValue){
    
    
						//退出
						break;
					}else{
    
    
						//否则就将temp放到集合中
						list.add(temp);
						temp -= 1;//temp左移
					}
				}
				list.add(mid);
				//向右扫描
				temp = mid +1;
				while(true){
    
    
					if(temp > arr.length - 1 || arr[temp] != findValue){
    
    
						//退出
						break;
					}else{
    
    
						//否则就将temp放到集合中
						list.add(temp);
						temp += 1;//temp左移
					}
				}
				return list;
			}
		}
}

Guess you like

Origin blog.csdn.net/qq_22155255/article/details/112847063
Recommended