|
1 | 1 | #include<stdio.h>
|
| 2 | +#include<stdlib.h> |
| 3 | + |
2 | 4 | int main() {
|
3 | 5 |
|
4 |
| - int n, a[30], item, i, j, mid, top, bottom; |
| 6 | + int n_terms, *arr, item, i, j, mid, top, bottom; |
5 | 7 |
|
6 | 8 |
|
7 | 9 | 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]); |
12 | 15 | }
|
13 | 16 |
|
14 | 17 | printf("\nEnter the item to search\n"); // Target element to be searched
|
15 | 18 | scanf("%d", &item);
|
16 | 19 | bottom = 1;
|
17 |
| - top = n; |
| 20 | + top = n_terms; |
18 | 21 |
|
19 | 22 | do {
|
20 | 23 | mid = (bottom + top) / 2;
|
21 |
| - if (item < a[mid]) |
| 24 | + if (item < arr[mid]) |
22 | 25 | 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 |
24 | 27 | else search in the lower part */
|
25 | 28 | bottom = mid + 1;
|
26 |
| - } while (item != a[mid] && bottom <= top); |
| 29 | + } while (item != arr[mid] && bottom <= top); |
27 | 30 |
|
28 |
| - if (item == a[mid]) { |
| 31 | + if (item == arr[mid]) { |
29 | 32 | 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); |
31 | 34 | } else {
|
32 |
| - printf("\n Search failed\n %d not found\n", item); |
| 35 | + printf("Search failed\n%d not found\n", item); |
33 | 36 | }
|
34 | 37 | return 0;
|
35 | 38 | }
|
0 commit comments