Skip to content

Commit 91b0f6a

Browse files
authored
Update BinarySearch.c
1 parent 7b27f58 commit 91b0f6a

File tree

1 file changed

+37
-40
lines changed

1 file changed

+37
-40
lines changed

src/c/BinarySearch.c

Lines changed: 37 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,43 @@
11
#include<stdio.h>
2-
#define SIZE 100
3-
4-
int BinarySearch(int array[], int size, int searched)
5-
{
6-
int start, middle, end;
7-
start = 0;
8-
end = size - 1;
9-
middle = end / 2;
10-
11-
while (start < end && array[middle] != searched)
12-
{
13-
if (searched > array[middle]) // new start
14-
start = middle + 1;
15-
16-
if (searched < array[middle]) // new end
17-
end = middle - 1;
18-
19-
// new middle
20-
middle = (start + end) / 2;
21-
}
22-
23-
if (array[middle] == searched)
24-
return middle;
25-
26-
return -1;
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;
2725
}
2826

29-
int main()
30-
{
31-
int searche;
32-
int arraySize = 10;
33-
int array[SIZE] = {1, 5, 10, 12, 18, 22, 87, 90, 112, 129};
34-
35-
printf("Please provide the number you want to search for: ");
36-
scanf("%d", &searche);
37-
38-
int pos = BinarySearch(array, arraySize, searche);
39-
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+
4037
if (pos != -1)
41-
printf("Found in position = %d.\nValue = %d\n", pos, array[pos]);
42-
else
43-
printf("Not found\n");
44-
38+
printf("Found in position = %d.\nValue = %d\n", pos, array[pos]);
39+
else
40+
printf("Not found\n");
41+
4542
return 0;
4643
}

0 commit comments

Comments
 (0)