/////
Search
Duplicate
📗

Binary Search

C

1. recursive function

int binary_search(int *arr, int start, int end, int key) { if (start > end ) return (0); int mid = (start + end) / 2; if (arr[mid] == key) return (1); else if (arr[mid] > key) binary_search(arr, start, mid - 1, key); else binary_search(arr, mid + 1, end, key); }
C
복사

2. iterative function

int binary_search(int *arr, int length, int key) { int start = 0; int end = length -1; int mid; while (end >= start) { mid = (start + end) / 2; // 중앙 값 if (arr[mid] == key) return (1); else if (arr[mid] > key) end = mid - 1; else start = mid + 1; } return (0); }
C
복사

C++

#include <algorithm> binary_search(data_arr, data_arr + n, search_value)
C
복사