본문 바로가기
Algorithm

Binary Search

by orioncsy 2022. 10. 13.

Binary Search iteration way

//java Binary search
//iteration way
public class Solution { 
	public int binarySearch(int[] arr, int target) {
		int low=0;
		int high=arr.length-1;
		while(low<=high){
			int half=(low+high)/2;
			if(arr[half]==target) return half;
			else if(arr[half]<target) low=half+1;
			else high=half-1;
		}
		return -1;
	}
}

Binary Search recursive way

//java Binary search
//recursive way
public class Solution { 
	public int binarySearch(int[] arr, int target, int low, int high) {
		if(low<=high){
			int half=(low+high)/2;
			if(arr[half]==target) return half;
			else if(arr[half]<target) return binarySearch(arr, target, half+1, high);
			else return binarySearch(arr,target,low, half-1);
		}
		return -1;
	}
}

'Algorithm' 카테고리의 다른 글

Rest API  (0) 2022.10.20
LSCS  (0) 2022.10.18
Heap Sort  (0) 2022.10.11
Merge Sort  (0) 2022.10.11
Radix Sort  (0) 2022.10.11