Friday, May 24, 2019

Linear & Binary Search C Program and Algorithm

For many other Language Programs related to microprocessor 8086  , C++ and Data structure visit our  BLOG 

Linear Search Algorithm: (useful for unsorted data list and fast for small data list)

   1. initialize p =-1
    2. set i=0
    3. repeate step 4 while (i<n)
    4.i f a[i] =val then set p =i print p and go to step 6
    5. else print value not present in array
    6. exit


Binary Search Algorithm: (useful for sorted(ascending) data list and fast for large data list)

    1. start
    2. initialize p =-1 ,beg= 0(lower bound) , end = upper bound
    3. repeate step 4  and step 3 while (beg<= end)
    4.if a[mid] =val  then  srt  end = mid-1     else   set   beg= mid+1  (end if and while loop)
    5. if beg>end  then print value not present in array else print value present in array
    6. exit

    
    Program of Linear and Binary Search:
j   
r    Linear Search Program

#include <stdio.h>
#include<conio.h>
void main()
{
//here n=10   arr[ -->   10 ß ]
int arr[10] ,p= -1,num ,found =0 ,i   ;
printf(“enter elements”);
for(i=0;i<10;i++)
{
scanf(“%d”,&arr[i]);
}
printf(“enter number to search ”);
scanf(“%d”,&num);
for(i=0;i<10;i++)
{
if ( arr[i==num)
{
found=1;
p = I;
printf(“ number found at position =  %d”,i+1);
break;
}
}
if(found==0)
{
printf(“ number not found”);
}
}

     Binary Search Program:

#include <stdio.h>
#include<conio.h>
void main()
{
int arr[10] ,beg,end,mid,val, i   ;
printf(“enter elements”);
for(i=0;i<10;i++)
{
scanf(“%d”,&arr[i]);
}
printf(“enter number to search ”);
scanf(“%d”,&num);
while(beg<=end)
{
mid = (beg+end)/2;
beg=0;end=10-1;
if(a[mid]<val)
{
beg =  mid+1;
}
else if (a[mid]==val)
{
printf(“element found at position %d ”,mid+1);
break;
}
else
(
end =mid-1;
}
mid=(beg +end )/2;
if(beg>end)
{
printf(“ element not found”);
}

For many other Language  Programs related to microprocessor 8086  , C++ and Data structure visit our  BLOG 

There are programs of bubble , selection , linear search , pop, push ,etc for data structures


No comments:

Post a Comment