Binary search (ideas + code)

variable:

left、right、mid、index、value

Ideas:

If it is bigger than arr[mid], go to the right;

If it is smaller than arr[mid], go left;

Queries with multiple target values

Define a temp pointer

Find out whether there are the same elements on the left and right of mid, and if so, add them to the set (loop)

code:

package search;

import java.util.ArrayList;
import java.util.List;

public class BinarySearch {
	public static void main(String[] args) {
		int[] arr = {1,8,10,89,1000,1234,1234};
		List<Integer> ls = binartSearch(arr, 0, arr.length - 1, 1234);
		System.out.print(ls);
		
	}
	public static List<Integer> binartSearch(int[] arr, int left, int right, int findValue) {
		if(left > right) {
			System.out.print("没有找到!");
			return null;
		}
		int mid = (left + right) / 2;
		if(arr[mid] > findValue) {
			return binartSearch(arr, left, mid - 1, findValue);
		}else if(arr[mid] < findValue) {
			return binartSearch(arr, mid + 1, right, findValue);
		}else {
			List<Integer> resIndexList =  new ArrayList<Integer>();
			int temp = mid-1;
			while(true) {
				if(temp < 0 || arr[temp] != findValue) {
					break;
				}
				resIndexList.add(temp);
				temp--;
			}
			resIndexList.add(mid);
			temp=mid+1;
			while(true) {
				if(temp > arr.length - 1 || arr[temp] != findValue) {
					break;
				}
				resIndexList.add(temp);
				temp++;
			}
			return resIndexList;
		}
		
	}
	
	
}

Guess you like

Origin blog.csdn.net/qq_56127002/article/details/131619445