The Program in C to search an element in 1-d array using binary search method is given below:
#include <stdio.h>
int binarySearch(int a[], int n, int x) {
int left = 0, right = n - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (a[mid] == x) {
return mid;
} else if (a[mid] < x) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
int main() {
int n, i, x, index;
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
int a[n];
printf("Enter the elements of the array in sorted order: ");
for (i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
printf("Enter the element to search for: ");
scanf("%d", &x);
index = binarySearch(a, n, x);
if (index == -1) {
printf("Element %d not found in the array\n", x);
} else {
printf("Element %d found at index %d\n", x, index);
}
return 0;
}
Output:
Enter the number of elements in the array: 5
Enter the elements of the array in sorted order: 1
4
7
9
10
Enter the element to search for: 7
Element 7 found at index 2
Pro-Tips💡
This program prompts the user to enter the number of elements in the array and the elements themselves.
It then prompts the user to enter the element to search for and call the binarySearch function which takes array, its size and the element to be searched as arguments.
The function uses a while loop to repeatedly divide the portion of the array being searched in half, until the search element is found or the search area is exhausted.
If the element is found, the function returns the index at which it was found. If the element is not found, the function returns -1.
The main function then checks the returned value and prints the result. Note that this program assumes that the input array is already sorted in ascending order.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.