#include <stdio.h> int main() { int A[] = {2,2,6,8,10,11}; int x = 2; int n = 6; int result = -1; int index = binarySearch(A,n,x); if(index == -1) { printf("%d is not found at index %d",x,index); } else { printf("%d is found at index %d",x,index); } return 0; } int binarySearch(int A[],int n,int x){ int start = 0, end = n-1, option,result = -1; printf("Choose option:1 for first occurrence \nChoose option:2 for last occurrence\n"); printf("Enter any option to find first or last occurrence of an element:"); scanf("%d",&option); while(start <= end){ int mid = (start + end)/2; if(option == 1){ if(x == A[mid]){ result = mid; end = mid-1; } else if(x < A[mid]){ end = mid-1; } else{ ...
Comments
Post a Comment