오직 정렬되어씨는 Data값에서 Binary search를 쓰면 더 빨리 찾을 수 있다.
일반적인 탐색은 O(n)이 걸리지만 Binary search는 O(log n)이 된다.
<재귀 코드>
#include <iostream>
#include <unordered_map>
using namespace std;
int vect[8] = { 1,1,2,5,7,9,15,20 };
int target = 7;
void binary_search(int start, int end) {
int mid = (start + end) / 2;
if (start > end) {
cout << "못찾음";
return;
}
if (vect[mid] == target) {
cout << mid << "index";
return;
}
if (vect[mid] < target) {
binary_search(mid + 1, end);
}
else {
binary_search(start, mid - 1);
}
}
int main() {
binary_search(0, 7);
return 0;
}
<while문 코드>
#include <iostream>
#include <unordered_map>
using namespace std;
int vect[8] = { 1,1,2,5,7,9,15,20 };
int target = 7;
int main() {
int start = 0;
int end = 7;
while (1) {
int mid = (start + end) / 2;
if (start > end) {
cout << "못찾음";
return 0;
}
if (vect[mid] == target) {
cout << mid << "index";
return 0;
}
if (vect[mid] < target) {
start = mid + 1;
}
else {
end = mid - 1;
}
}
return 0;
}728x90
'알고리즘 > 코딩 & 알고리즘 공부' 카테고리의 다른 글
| [C++] Heap 자료구조 (0) | 2022.04.21 |
|---|---|
| [C++] Union Find & MST & 크루스칼 (Kruskal) 알고리즘 정리 (0) | 2022.04.20 |
| [C++] Priority_queue vs Queue, pair (0) | 2021.07.24 |
| [C++] find, substr, erase, insert (0) | 2021.07.23 |
댓글