Skip to content

Commit 9c9cce3

Browse files
authored
Merge pull request kelvins#305 from IrineuAlmeidaJr/main
add: Binary Search in C
2 parents de51acd + c5bab04 commit 9c9cce3

File tree

2 files changed

+45
-2
lines changed

2 files changed

+45
-2
lines changed

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -183,8 +183,8 @@ In order to achieve greater coverage and encourage more people to contribute to
183183
<tr>
184184
<td><a href="https://en.wikipedia.org/wiki/Binary_search_algorithm">Binary Search</a></td>
185185
<td> <!-- C -->
186-
<a href="./CONTRIBUTING.md">
187-
<img align="center" height="25" src="./logos/github.svg" />
186+
<a href="./src/c/BinarySearch.c">
187+
<img align="center" height="25" src="./logos/c.svg" />
188188
</a>
189189
</td>
190190
<td> <!-- C++ -->

src/c/BinarySearch.c

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
#include<stdio.h>
2+
3+
int BinarySearch(int array[], int size, int value) {
4+
int start = 0;
5+
int end = size - 1;
6+
int middle = end / 2;
7+
8+
while (start < end && array[middle] != value) {
9+
// new start
10+
if (value > array[middle])
11+
start = middle + 1;
12+
13+
// new end
14+
if (value < array[middle])
15+
end = middle - 1;
16+
17+
// new middle
18+
middle = (start + end) / 2;
19+
}
20+
21+
if (array[middle] == value)
22+
return middle;
23+
24+
return -1;
25+
}
26+
27+
int main() {
28+
int value;
29+
int array[] = {1, 5, 10, 12, 18, 22, 87, 90, 112, 129};
30+
size_t size = sizeof(array) / sizeof(array[0]);
31+
32+
printf("Please provide the number you want to value for: ");
33+
scanf("%d", &value);
34+
35+
int pos = BinarySearch(array, size, value);
36+
37+
if (pos != -1)
38+
printf("Found in position = %d.\nValue = %d\n", pos, array[pos]);
39+
else
40+
printf("Not found\n");
41+
42+
return 0;
43+
}

0 commit comments

Comments
 (0)