You are on page 1of 6

Experiment No.

Date Of Submission:

BINARY SEARCH

AIM : To implement the binary search using C.

ALGORITHM : STEP 1: Start the program. STEP 2: Declare the variables a[50] ,i , n ,j ,temp ,x ,low ,high ,mid ,flag=1. STEP 3: Get the value. STEP 4: The given elements to be searched. STEP 5: Initialize the low and high value. STEP 6: Check the condition while(low<high). STEP 7: To find middle value using mid= (low+high)/2. STEP 8: If (x == a [mid]) return middle. STEP 9: If(x>a [mid]) low=mid+1. STEP 10: If(x<a [mid]) high=mid-1. STEP 11: If the condition does not occur means the else value gets executed. STEP 12: Stop the program.

PROGRAM CODING: #include <stdio.h> #include<conio.h> void main() { int a[50],i,n,j,temp,x,low,high,mid,flag=1; clrscr(); printf("\n Enter the number of elements:"); scanf("%d",&n); printf("\n enter the number:"); for(i=0;i<n;i++) { scanf("%d",&a[i]); } for(i=0;i<n;i++) { for(j=0;j<n;j++) { if(a[i]<a[j]) { temp=a[i]; a[i]=a[j]; a[j]=temp; } } } printf("\n sorted number"); for(i=0;i<n;i++) printf("\n%d",a[i]); printf("\n enter the search elements:"); scanf("%d",&x);

low=0; high=n-1; while(low <=high) { mid=(low+high)/2; if(x<a[mid]) high=mid-1; else if(x>a[mid]) low=mid+1; else if(x==a[mid]) { printf("\nsearch elements is present\n"); flag=0; break; } } if (flag) printf("\search element is not present"); getch(); }

OUTPUT

You might also like