반응형
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <stack>
#include <deque>
#include <queue>
using namespace std;
int bS(int* arr, int len, int value) //binarySearch 함수
{
int start, mid, end;
start = 0;
end = len - 1;
while (1)
{
if (start > end) //검색에 실패한경우
{
cout << "탐색실패" << '\n';
break;
}
mid = (start + end) / 2;
if (arr[mid] == value) //원하는 값을 찾은 경우
{
return mid;
break;
}
else if (arr[mid] > value) //찾는 값보다 중앙값이 클경우
end = mid - 1; //중앙값-1을 end에 저장하여 다시 탐색
else if (arr[mid] < value) //찾는 값보다 중앙값이 작을경우
start = mid + 1; //중앙값+1을 start에 저장하여 다시 탐색
}
return -1;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int arr[100];
int arr2[5] = { 2,1,3,5,4 };
for (int i = 0; i < 100; i++) //배열안에 값 저장
{
arr[i] = i;
}
cout << binary_search(arr, arr + 100, 35)<<'\n'; //STL binary_search 사용한 예, 찾는 값이 있는지 bool로 반환
cout << bS(arr, 100, 45)<<'\n'; //인덱스를 반환하는 bS함수사용
cout << bS(arr2, 5, 3) << '\n';
return 0;
}
반응형
'Programming > Data Structure and Algorithm' 카테고리의 다른 글
삽입정렬 예제 주석포함 c++ (0) | 2022.01.20 |
---|---|
자료구조 탐색 기초 개념 정리 (0) | 2022.01.10 |
자료구조 정렬(Sorting) 기초 개념 정리 (0) | 2022.01.08 |
자료구조 우선순위큐(Priority Queue) 기초 개념 정리 (0) | 2022.01.06 |
자료구조 트리(Tree) 기초 개념정리 (0) | 2022.01.02 |