Binary Search solution using c language--programming_info problem 7

 Binary Search

This above example is just a reference picture. don't
think it as an input of an array.
you can give your own input.

#include<stdio.h>

int main()
 {

int arr[20],n,mid,ele,i;

printf("\nHow many elements:");

scanf("%d",&n);
printf("%d",n);
printf("\nEnter the elememts in sorted manner:");

for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}

for(i=0;i<n;i++)
{
printf("%d",arr[i]);
printf(" ");
}
printf("\nEnter the element to be searched for:");
scanf("%d",&ele);
printf("%d",ele);
mid=n/2;
if(ele<=arr[n-1])
{
if(arr[mid]>ele)
{   
      for(i=0;i<mid;i++)
     { 
      if(arr[i]==ele)
      {
       printf("\n\nPosition=%d",i);
       break;
      }
     }
}
else if(arr[mid]<ele)
{
    for(i=mid;i<n;i++)
    { 
     if(arr[i]==ele)
      {
       printf("\n\nPosition=%d",i);
       break;
      }
   
    }
}
else

printf("\n\nPosition=%d",mid);

}
else
printf("\nNo such element exists");
 return 0;
}
Share:

No comments:

Post a Comment

Translate

Recommended platforms

  1. codechef
  2. hackerrank
  3. codeforces
  4. leetcode
  5. hackerearth

Popular Posts

programming_info. Powered by Blogger.

Blog Archive

Recent Posts

other platforms

  • geeks for geeks
  • w3schools
  • codepen
  • skillshare
  • udemy

Pages

reader support Support