Binary Search of an element in an array of elements

seeniya 0 Tallied Votes 235 Views Share

Here is a binary search program quite simplified

#include<stdio.h>
#include<conio.h>

void swap(int a[],int n);
void main()
{
 int a[20],x,i,j,n;
 clrscr();
 printf("Enter the no. of elements :");
 scanf("%d",&n);
 printf("Enter the elements:");
 for(i=0;i<n;i++)
 scanf("%d",&a[i]);
 printf("After sorting :\n");
 swap(a,n);
 for(i=0;i<n;i++)
 printf("%d",a[i]);
 printf("Enter the element to be searched:");
 scanf("%d",&x);

 if(x==a[n/2])
    printf("PRESENT");
 else if(x<a[n/2])
 {
   for(i=0;i<n/2;i++)
    {
     if(x==a[i])
     {
      printf("PRESENT");
      break;
     }
     else
      printf("NOT PRESENT");
      break;
    }
 }

 else if(x>a[n/2])
  {
   for(i=(n/2)+1;i<n;i++)
    {
     if(x==a[i])
     {
      printf("PRESENT");
      break;
     }
     else
     printf("NOT PRESENT");
     break;
     }
   }
getch();
}

void swap(int a[],int n)
{
  int i,j,temp;
  for(i=0;i<n-1;i++)
 {
  for(j=i+1;j<n;j++)
  {
   if(a[i]>a[j])
    {
     temp=a[i];
     a[i]=a[j];
     a[j]=temp;
    }
   }
 }
}
seeniya 0 Newbie Poster

nice attempt.....Soorya

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.