Skip to content

Commit 905ed34

Browse files
committed
added a binary search code
1 parent b602447 commit 905ed34

File tree

1 file changed

+83
-0
lines changed
  • Search/BinarySearch/c

1 file changed

+83
-0
lines changed

Search/BinarySearch/c/BS.c

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
#include <stdio.h>
2+
3+
#define MAX 20
4+
5+
// array of items on which linear search will be conducted.
6+
int intArray[MAX] = {1,2,3,4,6,7,9,11,12,14,15,16,17,19,33,34,43,45,55,66};
7+
8+
void printline(int count) {
9+
int i;
10+
11+
for(i = 0;i <count-1;i++) {
12+
printf("=");
13+
}
14+
15+
printf("=\n");
16+
}
17+
18+
int find(int data) {
19+
int lowerBound = 0;
20+
int upperBound = MAX -1;
21+
int midPoint = -1;
22+
int comparisons = 0;
23+
int index = -1;
24+
25+
while(lowerBound <= upperBound) {
26+
printf("Comparison %d\n" , (comparisons +1) );
27+
printf("lowerBound : %d, intArray[%d] = %d\n",lowerBound,lowerBound,
28+
intArray[lowerBound]);
29+
printf("upperBound : %d, intArray[%d] = %d\n",upperBound,upperBound,
30+
intArray[upperBound]);
31+
comparisons++;
32+
33+
// compute the mid point
34+
// midPoint = (lowerBound + upperBound) / 2;
35+
midPoint = lowerBound + (upperBound - lowerBound) / 2;
36+
37+
// data found
38+
if(intArray[midPoint] == data) {
39+
index = midPoint;
40+
break;
41+
} else {
42+
// if data is larger
43+
if(intArray[midPoint] < data) {
44+
// data is in upper half
45+
lowerBound = midPoint + 1;
46+
}
47+
// data is smaller
48+
else {
49+
// data is in lower half
50+
upperBound = midPoint -1;
51+
}
52+
}
53+
}
54+
printf("Total comparisons made: %d" , comparisons);
55+
return index;
56+
}
57+
58+
void display() {
59+
int i;
60+
printf("[");
61+
62+
// navigate through all items
63+
for(i = 0;i<MAX;i++) {
64+
printf("%d ",intArray[i]);
65+
}
66+
67+
printf("]\n");
68+
}
69+
70+
void main() {
71+
printf("Input Array: ");
72+
display();
73+
printline(50);
74+
75+
//find location of 1
76+
int location = find(55);
77+
78+
// if element was found
79+
if(location != -1)
80+
printf("\nElement found at location: %d" ,(location+1));
81+
else
82+
printf("\nElement not found.");
83+
}

0 commit comments

Comments
 (0)