-
Notifications
You must be signed in to change notification settings - Fork 0
/
iterative_bsearch.c
70 lines (53 loc) · 929 Bytes
/
iterative_bsearch.c
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/*
* https://github.com/rafaelvanoni/C.git
*/
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#define MAX_LEN (20)
#define MAX_VAL (99)
int
ibs(int *array, int len, int n)
{
int l = 0, h = len - 1, m;
while (l <= h) {
m = l + (h-l)/2;
if (array[m] == n) {
return (m);
}
if (n > array[m]) {
l = m + 1;
} else {
h = m - 1;
}
}
return (-1);
}
int
cmp(const void *a, const void *b)
{
return (*(int *)a - *(int *)b);
}
int
main(int argc, char **argv)
{
int *array, len, n;
srand(time(NULL));
do {
len = rand() % MAX_LEN;
} while (len == 0);
array = calloc(len, sizeof (int));
for (int i = 0; i < len; i++) {
array[i] = rand() % MAX_VAL;
if (rand() % 2 == 0) {
n = array[i];
}
}
qsort(array, len, sizeof(int), cmp);
for (int i = 0; i < len; i++) {
printf("%d ", array[i]);
}
printf("\nfound %d at %d\n", n, ibs(array, len, n));
free(array);
return (0);
}