POP Lab Program 8
POP Lab Program 8
PROGRAM-8
Write a C Program to Implement linear search and binary search.
Procedure: Input N array elements and to find whether element is present or not.
Input: Array elements.
Expected Output: Successful search or unsuccessful search.
ALOGRITHM
Algorithm binary_search
Step 1: Start
Step 2: Read n
Step 3: Repeat for i=0 to n-1
Read a[i]
Step 4: read key
Step 5: Initialize low =0 high = n-1
Step 6: Repeat through step 6 while (low <= high)
mid = (low+ high)/2
if(key==a[mid])
found=1
else if(key>a[mid])
low=mid+1
else
high=mid-1
end while
Step 7: if(found ==1)
print “Item found”
else
print” Item not found”
Step 8: Stop
FLOWCHART
PROGRAM:-Binary Search
#include<stdio.h>
int main()
{
int i,n,a[10],mid,low,high,key, found=0;
printf("\n Enter the number of elements:\n");
scanf("%d", &n);
printf("Enter the array element in the ascending order\n");
for(i=0;i<n;i++)
{
scanf("%d", &a[i]);
}
printf("\n Enter the key element to be searched\n");
scanf("%d", &key);
low=0;
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if(key==a[mid])
{
found=1;
break;
}
else if(key>a[mid])
low=mid+1;
else
high=mid-1;
}
if(found ==1)
printf(“Item found in position : %d”,mid+1);
else
printf("\n Item not found\n");
}
OUTPUT:
RUN 1:
Enter the number of elements:
5
Enter the array element in the ascending order
10
20
30
40
50
OUTPUT:
Enter the number of elements:
5
Enter the array element in the ascending order
11
66
33
88
23
Enter the key element to be searched
88
Item found in position : 4