forked from yunghsianglu/CProgramExercise
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarysearch.c
More file actions
99 lines (91 loc) · 1.75 KB
/
Copy pathbinarysearch.c
File metadata and controls
99 lines (91 loc) · 1.75 KB
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#define RANGE 100
int * arrGen(int size);
// generate a sorted array of integers
static int binarySearchHelp(int * arr, int low, int high, int key)
{
if (low > high)
{
return -1;
}
int ind = (low + high) / 2;
if (arr[ind] == key)
{
return ind;
}
if (arr[ind] > key)
{
return binarySearchHelp(arr, low, ind - 1, key);
}
return binarySearchHelp(arr, ind + 1, high, key);
}
int binarySearch(int * arr, int len, int key)
{
return binarySearchHelp(arr, 0, len - 1, key);
}
void printArray(int * arr, int len);
int main(int argc, char * * argv)
{
if (argc < 2)
{
printf("need a positive integer\n");
return EXIT_FAILURE;
}
int num = strtol(argv[1], NULL, 10);
if (num <= 0)
{
printf("need a positive integer\n");
return EXIT_FAILURE;
}
int * arr = arrGen(num);
printArray(arr, num);
int count;
for (count = 0; count < 10; count ++)
{
int key;
if ((count % 2) == 0)
{
key = arr[rand() % num];
}
else
{
key = rand() % 100000;
}
printf("search(%d), result = %d\n",
key, binarySearch(arr, num, key));
}
free (arr);
return EXIT_SUCCESS;
}
int * arrGen(int size)
{
if (size <= 0)
{
return NULL;
}
int * arr = malloc(sizeof(int) * size);
if (arr == NULL)
{
return NULL;
}
srand(time(NULL)); // set the seed
int ind;
arr[0] = rand() % RANGE;
for (ind = 1; ind < size; ind ++)
{
arr[ind] = arr[ind - 1] + (rand() % RANGE) + 1;
}
return arr;
}
void printArray(int * arr, int len)
{
int ind;
for (ind = 0; ind < len; ind ++)
{
printf("%d ", arr[ind]);
}
printf("\n\n");
}