-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarySearch.c
More file actions
executable file
·63 lines (52 loc) · 2.15 KB
/
binarySearch.c
File metadata and controls
executable file
·63 lines (52 loc) · 2.15 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
/*
Divide in half
A fast way to search a sorted array is to use a binary search.
The idea is to look at the element in the middle. If the key is
equal to that, the search is finished. If the key is less than
the middle element, do a binary search on the first half.
If it's greater, do a binary search of the second half.
Performance
The advantage of a binary search over a linear search is astounding
for large numbers. For an array of a million elements, binary search, O(log N),
will find the target element with a worst case of only 20 comparisons.
Linear search, O(N), on average will take 500,000 comparisons to find the element.
Probably the only faster kind of search uses hashing, a topic that isn't covered in these notes.
This performance comes at a price - the array must be sorted first. Because sorting
isn't a fast operation, it may not be worth the effort to sort when there are only a few searches.
*/
#define MAX 128
int binarySearch(int sortedArray[], int first, int last, int key) {
// function:
// Searches sortedArray[first]..sortedArray[last] for key.
// returns: index of the matching element if it finds key,
// otherwise -(index where it could be inserted)-1.
// parameters:
// sortedArray in array of sorted (ascending) values.
// first, last in lower and upper subscript bounds
// key in value to search for.
// returns:
// index of key, or -insertion_position -1 if key is not
// in the array. This value can easily be
// transformed into the position to insert it.
while (first <= last) {
int mid = (first + last) / 2; // compute mid point.
if (key > sortedArray[mid])
first = mid + 1; // repeat search in top half.
else if (key < sortedArray[mid])
last = mid - 1; // repeat search in bottom half.
else
return mid; // found it. return position /////
}
return -(first + 1); // failed to find key
}
int main()
{
int a[MAX];
int i;
int index;
for (i = 0; i < MAX; i++)
a[i] = i;
// Cannot find MAX
index = binarySearch(a, 0, MAX - 1, MAX);
return 0;
}