Untitled
unknown
plain_text
12 days ago
663 B
2
Indexable
#include<stdio.h> int binarysearch(int arr[],int n, int key) { int l=0, r=n-1; while (l<=r) { int mid= l+(r-l)/2; if(arr[mid]==key) { return mid; } else if(arr[mid]<key) { l= mid+1; } else{ r=mid-1; }} return -1; } int main() { int n, key; printf("Enter the size of the array: "); scanf("%d", &n); int arr[n]; printf("Enter the elements in the sorted array: "); for (int i = 0; i < n; i++) { scanf("%d", &arr[i]); } printf("Enter the key to search: "); scanf("%d", &key); int result = binarysearch(arr, n, key); if (result != -1) { printf("Element %d found at index %d \n", key, result); } else { printf("Element %d not found in the array \n", key); } return 0; }
Editor is loading...
Leave a Comment