Algorithm - Binary Search (C)

  • 정렬된 배열에 대해 사용 가능

Example

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
32
33
34
35
36
37
38
39
40
41
42
43
#include <stdio.h>
#include <stdlib.h>

int compare(const void* a, const void* b) {
if (*(int*)a > *(int*)b) return 1;
else if (*(int*)a < *(int*)b) return -1;
return 0;
}

int binsearch(int data[], int n, int key) {
int low, high, mid;

low = 0;
high = n-1;

while (low <= high) {
mid = (low+high) / 2;
if (key == data[mid]) return 1;
else if (key < data[mid]) high = mid-1;
else if (key > data[mid]) low = mid+1;
}

return 0;
}

int n, key;

int main() {
scanf("%d", &n);
int arr[n];
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

qsort(arr, n, sizeof(int), compare);

for (int j = 0; j < n; j++) {
printf("%d ", arr[j]);
}

scanf("%d", &key);
printf("\nfind key: %s\n", binsearch(arr, n, key) ? "Exist" : "None");
}
  • input
1
2
3
10
9 2 6 5 1 7 3 4 8 1
5
  • output
1
2
1 1 2 3 4 5 6 7 8 9 
find key: Exist