Wednesday, 20 August 2014

Filled Under:

C Program to implement Linear and Binary Search

Share

C Program to implement Linear and Binary Search

Linear and binary searching is a similar type of searching because it search only in sorted elements list or array.

C Program to implement Linear and Binary Search

#include <stdio.h>
#include <conio.h>
void main()
{
 int arr[20], i, n, element, opt, pos, flag=0, beg, mid, end;
 clrscr();
 printf("How many elements? ");
 scanf("%d",&n);
 printf("nEnter %d sorted elements  : ",n);
 for (i=0; i<n; i++)
 scanf("%d",&arr[i]);
 printf("nThe entered array is :n");
  for (i=0; i<n; i++)
 {
  printf("%dt",arr[i]);
 }
 for (i=1; i<n; i++)
 {
  if (arr[i-1]>arr[i])
  {
   printf("nThe array entered isn't sorted!");
   printf("nExiting");
   getch();
   exit();
  }
 }
 printf("nnt **MAIN MENU**");
 printf("n1. Search using Linear Search");
 printf("n2. Search using Binary Search");
 printf("n Enter an option : ");
 scanf("%d",&opt);
 printf("nEnter the element to search : ");
 scanf("%d",&element);

 if (opt==1)
 {
  for (i=0; i<n; i++)
   {
    if (element==arr[i])
    {
     pos=i+1;
     flag=1;
     printf("The element is at postion %d",pos);
    }
   }
 }

 else if (opt==2)
 {
  beg=0;
  end=n;
  for (mid=(beg+end)/2;beg<=end;mid=(beg+end)/2)
  {
   if (arr[mid]==element)
   {
    printf("nThe element is at position %d",mid+1);
    flag=1;
    break;
   }
   if (arr[mid]>element)
    end=mid-1;
   else
    beg=mid+1;
  }

 if (flag==0)
     {
  printf("nn##Element not in array##");
     }
 }

 else printf("nn ERROR!! INVALID INPUT");
 getch();
}
Output: