Wednesday, October 3, 2018

CPL 6 - BINARY SEARCH

6. Introduce 1D Array manipulation and implement Binary search.

Algorithm:

Step 1:[read the value of N]
     Read N

Step 2:[Enter the elements in ascending order]
For i=0 to N-1 is to be read from the keyboard

Step 3:[Enter the one element for searching that could be a key element]

Step 4: initially set low=0 and high=N

Step 5:[Find out the middle value]
           Mid=(low+hogh)/2;

Step 6: Check key value is lesser than the middle value go to step 7
       Check key value is greater than the middle value go to step 8
     
Step 7: high=mid-1

Step 8: low =mid+1;

Step 9: if key value and mid-value are same then go to step 10 if not go to step 11

Step 10: successful search

Step 11: not searched the key element

Step 12: stop

FLOWCHART:( click on image to zoom )






PROGRAM:


#include<stdio.h>
#include<string.h>

void main()
{
char name[50][50],key[50];
int n,i,low,high,mid,found=0;
printf("How many names to Read:\n");
scanf("%d",&n);
printf("Enter the Names in ascending order:\n");
for(i=0;i<n;i++)
{
scanf("%s",name[i]);
}
printf("\nType the name to be searched:");
scanf("%s",key);

low=0;
high=n-1;
while(low<=high && !found)
{
mid=(low+high)/2;
if(strcmp(name[mid],key)==0)
found=1;
    else if(strcmp(name[mid],key)<0)
low=mid+1;
    else
high=mid-1;
}

if(found==1)
printf("\nSearch successful and Name found in the list at  position:%d",mid+1);
else
printf("Name not found and search Unsuccessful....!");

}


OUTPUT:( click on image to zoom )



No comments:

Post a Comment