Finding first or last occurrence of an element in array

#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{
      start = mid+1;
    }
  }
 
  if(option == 2){
    if(x == A[mid]){
      result = mid;
      start = mid+1;
    }
    else if(x < A[mid]){
      end = mid-1;
    }
    else{
      start = mid+1;
    }
  }
  }
  return result;
}

OUTPUT:
Choose option:1 for first occurrence
Choose option:2 for last occurrence
Enter any option to find first or last occurrence of an element:1
2 is found at index 0

Comments

Popular posts from this blog

Finding the second largest in an array