Skip to content

Commit 579738f

Browse files
committed
dynamic memory allocation and modified variable names
1 parent c59c98c commit 579738f

File tree

1 file changed

+15
-12
lines changed

1 file changed

+15
-12
lines changed

search/Binary_Search.c

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,38 @@
11
#include<stdio.h>
2+
#include<stdlib.h>
3+
24
int main() {
35

4-
int n, a[30], item, i, j, mid, top, bottom;
6+
int n_terms, *arr, item, i, j, mid, top, bottom;
57

68

79
printf("Enter how many elements you want:\n"); // no of elements
8-
scanf("%d", &n);
9-
printf("Enter the %d elements in ascending order\n", n);
10-
for (i = 0; i < n; i++) {
11-
scanf("%d", &a[i]);
10+
scanf("%d", &n_terms);
11+
arr = (int*)malloc(sizeof(int)*n_terms);
12+
printf("Enter the %d elements in ascending order\n", n_terms);
13+
for (i = 0; i < n_terms; i++) {
14+
scanf("%d", &arr[i]);
1215
}
1316

1417
printf("\nEnter the item to search\n"); // Target element to be searched
1518
scanf("%d", &item);
1619
bottom = 1;
17-
top = n;
20+
top = n_terms;
1821

1922
do {
2023
mid = (bottom + top) / 2;
21-
if (item < a[mid])
24+
if (item < arr[mid])
2225
top = mid - 1; // Here we are dividing the array into two equal parts
23-
else if (item > a[mid]) /* if target element > mid part of array , we do the search in the upper part of the array
26+
else if (item > arr[mid]) /* if target element > mid part of array , we do the search in the upper part of the array
2427
else search in the lower part */
2528
bottom = mid + 1;
26-
} while (item != a[mid] && bottom <= top);
29+
} while (item != arr[mid] && bottom <= top);
2730

28-
if (item == a[mid]) {
31+
if (item == arr[mid]) {
2932
printf("Binary search successfull!!\n");
30-
printf("\n %d found in position: %d\n", item, mid + 1);
33+
printf("%d found in position: %d\n", item, mid + 1);
3134
} else {
32-
printf("\n Search failed\n %d not found\n", item);
35+
printf("Search failed\n%d not found\n", item);
3336
}
3437
return 0;
3538
}

0 commit comments

Comments
 (0)