DAA - 5.Binary Search Program with Output

 

Binary Search Program 

 

Algorithm:

Step 1: Start the process.

Step 2: Declare the variables.

Step 3: Enter the list of elements to be searched using the get function.

Step 4: Divide the array list into two halves the lower array list and upper arraylist.

Step 5: It works by comparing a search key k with the arrays middle element a[m].

Step 6: If they match the algorithm stops; otherwise the same operation is repeated

recursively for the first half of the array if k < a[m] and the second half if k > a[m].

Step 7: Display the searching results

Step 8: Stop the process.



SOURCE CODE : 

#include<stdio.h>

#include<conio.h>

#define size 10

#include<time.h>

void main()

{

int arr[size],num,i,n,low,high,mid,found=0;

clock_t start,end;

double cpu_time_used;


clrscr();

start=clock();

printf("Enter number of elements: ");

scanf("%d",&n);

printf("\n Enter the elements: ");

for(i=0;i<n;i++)

{

 scanf("%d",&arr[i]);

}

printf("\n The array is: ");

  for(i=0;i<n;i++)

   printf("\n %d\t",arr[i]);

       printf("\n\n Enter the element that has to be searched: ");

       scanf("%d",&num);

       end=clock();

  cpu_time_used=((double) (end-start))/CLOCKS_PER_SEC;

       printf(" The elapsed time is %f seconds",cpu_time_used);

       low=0,high=n-1;

  while(low<=high)

 {

      mid=(low+high)/2;

      if(arr[mid]==num)

      {

printf("\n %d is present in the array at the position  %d ",num,mid+1);

found=1;

break;

      }

      else if(arr[mid]>num)

 high=mid-1;

else

 low=mid+1;

}

     if(low>high && found==0)

     printf("\n %d does not exist in the array",num);

     getch();

}



OUTPUT : 



Post a Comment

0 Comments