-
[Algorithm] - 이진 탐색(Binary Search)Data Structure, Algorithm 2016. 3. 5. 12:51
#include <iostream> using std::cout; using std::endl; int BinarySearch(int arr[], int len, int target) { int first = 0; int last = len - 1; int mid; while (first <= last) { mid = (first + last) ⁄ 2; if (target == arr[mid]) { return mid; } else { if (target < arr[mid]) { last = mid - 1; } else { first = mid + 1; } } } return -1; } int main(void) { int arr[] = { 1, 3, 5, 7, 9 }; int index = BinarySearch(arr, sizeof(arr) ⁄ sizeof(arr[0]), 7); if (index == -1) { cout << "Search Failed" << endl; } else { cout << "Target Save Index : " << index << endl; } index = BinarySearch(arr, sizeof(arr) ⁄ sizeof(arr[0]), 4); if (index == -1) { cout << "Search Failed" << endl; } else { cout << "Target Save Index : " << index << endl; } }
'Data Structure, Algorithm' 카테고리의 다른 글
[Algorithm] - 사각형 가로 세로 비율 구하기(Aspect Rectangle Ratio) (0) 2017.02.20 [Algorithm] - 오름차순(Ascending), 내림차순(Descending) 정렬 (0) 2016.03.08 [Algorithm] - 선형 탐색(Linear Search) (0) 2016.03.05