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
- 구현
- 파이썬
- dynamic programming
- two pointers
- database
- SQL
- Math
- Class
- Stack
- Binary Search
- Method
- implement
- java
- Counting
- simulation
- Data Structure
- bit manipulation
- hash table
- 자바
- string
- greedy
- array
- 코딩테스트
- 코테
- geometry
- sorting
- Matrix
- Binary Tree
- Tree
- Number Theory
Archives
- Today
- Total
코린이의 소소한 공부노트
Binary Search (iterative) 본문
1. Problem
- 정렬된 배열에서 x를 찾아보자
2. Input
1) 양수 n
2) 오름차순으로 정렬된 배열 S indexed from 1 to n
3) key x
3. Output
1) x의 위치
2) x가 없다면 0을 반환
4. PseudoCode
index binsearch(int n, const keytype S[], keytype x, index location){
index low, high, mid;
low = 1; high = n; location = 0;
while(low<=high && location==0){
mid = floor((low+high)/2);
if(x==S[mid])
location = mid;
else if(x<S[mid])
high = mid - 1;
else
low = mid + 1;
}
return location;
}
5. Example
class Test {
public static void main(String[] args){
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int a = 7;
System.out.println(a + "의 위치: " + binsearch(arr.length, arr, a)); // 7의 위치: 7
}
static int binsearch(int n, int[] S, int x){
int low=0, high=n-1, mid, location = 0;
while(low<=high && location==0){
mid = (low+high)/2;
if(x==S[mid])
location = mid;
else if(x<S[mid])
high = mid - 1;
else
low = mid + 1;
}
return location+1;
}
}
'Back-End > Algorithm' 카테고리의 다른 글
n-th Fibonacci Term (Iterative) (0) | 2023.02.22 |
---|---|
n-th Fibonacci Term (Recursive) (0) | 2023.02.22 |
Matrix Multiplication (0) | 2023.02.22 |
Exchange Sort (0) | 2023.02.22 |
Add Array Members (0) | 2023.02.22 |