C Program to Implement Binary Search
Write C Program to Implement Binary Search
// C Program to Implement Binary Search #include <stdio.h> int BinarySearch(int A[], int low, int high, int key) { while(low <= high) { int mid = (low + high) / 2; if(A[mid] == key) { return mid; } else if(A[mid] > key) { high = mid - 1; } else { low = mid + 1; } } return -1; } int main() { int A[] = { 2, 3, 4, 10, 40 }; int n = sizeof(A) / sizeof(A[0]); int key, i; printf("\nArray Elements :--> "); for (i = 0; i < n; i++) printf("%d ", A[i]); printf("\nEnter Element to Search :--> "); scanf("%d", &key); int result = BinarySearch(A, 0, n - 1, key); if(result == -1) { printf("\nElement is not present in array"); } else { printf("\nElement is present at index %d", result); } return 0; }
Output:
Run 1:
Array Elements :--> 2 3 4 10 40
Enter Element to Search :--> 4
Element is present at index 2
Run 2:
Array Elements :--> 2 3 4 10 40
Enter Element to Search :--> 11
Element is not present in array