Skip to main content
Search
Search This Blog
Livecodo
Pages
Home
Courses
Blog
About us
More…
Share
Get link
Facebook
X
Pinterest
Email
Other Apps
May 02, 2024
Write a c program to perform binary search.
#include
int binarySearch(int arr[], int left, int right, int x) { while (left <= right) { int mid = left + (right- left) / 2; if (arr[mid] == x) { return mid; } if (arr[mid] < x) { left = mid + 1; } else { right = mid- 1; } } return-1; } int main() { int arr[] = {2, 3, 4, 10, 40}; int n = sizeof(arr) / sizeof(arr[0]); int x; printf("Enter the element to search: "); scanf("%d", &x); int result = binarySearch(arr, 0, n- 1, x); if (result ==-1) { printf("Element is not present in array\n"); } else { printf("Element is present at index %d\n", result); } return 0; }
Popular Posts
March 26, 2024
Dynamic Memory allocation in C
May 18, 2024
Searching and sorting Algorithm in C