Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 | 31 |
Tags
- array
- sorting
- string
- hash table
- Math
- Stack
- 구현
- greedy
- Class
- Method
- Counting
- Binary Tree
- SQL
- Binary Search
- dynamic programming
- java
- Tree
- implement
- 자바
- geometry
- two pointers
- bit manipulation
- 코딩테스트
- Data Structure
- 코테
- 파이썬
- Matrix
- Number Theory
- simulation
- database
Archives
- Today
- Total
코린이의 소소한 공부노트
Binary Search (recursive) 본문
1. Problem
- 크기가 n인 정렬된 배열 S에서 x를 찾아보자
2. Input
1) 양수 n
2) 오름차순으로 정렬된 S indexed from 1 to n
3) key x
3. Output
1) x의 위치
2) S에 x가 없다면 0
4. PseudoCode
index location(index low, index high){
index mid;
if(low>high)
return 0;
else{
mid = floor((low+high)/2);
if(x==S[mid])
return mid;
else if(x<S[mid])
return location(low,mid-1);
else
return location(mid+1,high);
}
}
5. Example
class Test {
public static void main(String[] args){
int[] arr = {10,12,13,14,18,20,25,27,30,35,40,45,47}; // 중앙값: 25
int a = 18;
System.out.println(a + "의 위치: " + location(0, arr.length-1, arr, a)); // 18의 위치: 5
} // 비교 순서
// 25 -> 13 -> 18
static int location(int low, int high, int[] S, int x) {
int answer;
if(low>high) answer = 0;
else {
int mid = (low+high)/2;
if(x==S[mid]) answer = mid+1; // 실제는 0-indexed, 문제에서 요구하는 것은 1-indexed
else if(x<S[mid]) answer = location(low,mid-1, S, x);
else answer = location(mid+1,high, S, x);
}
return answer;
}
}
- worst T(n) = lg 2 + 1
'Back-End > Algorithm' 카테고리의 다른 글
Merge Sort (recursive, less memory, in-place) (0) | 2023.02.24 |
---|---|
Merge Sort (recursive) (0) | 2023.02.23 |
Divide and Conquer (0) | 2023.02.23 |
n-th Fibonacci Term (Iterative) (0) | 2023.02.22 |
n-th Fibonacci Term (Recursive) (0) | 2023.02.22 |