Download as rtf, pdf, or txt
Download as rtf, pdf, or txt
You are on page 1of 3

IMPLEMENTATION OF BINARY SEARCH NON-RECURSIVE CODING

090606123097

#include<stdio.h> #include<conio.h> #include<process.h> #include<time.h> int a[10],key,n; int binary(int a[10],int key); void main() { int i,j,temp,flag,choice; clock_t start,end; clrscr(); start=clock(); printf("\nEnter the no of elements of the array"); scanf("%d",&n); printf("\Is the array sorted?Press 1 for sorted array and pres 0 for unsorted array"); scanf("%d",&choice); switch(choice) { case 1: printf("\nEnter the elements of the array"); for(i=0;i<n;i++) scanf("%d",&a[i]); printf("\nEnter the element to be found"); scanf("%d",&key); flag=binary(a,key); break; case 0: printf("\nEnter the elements of the array"); for(i=0;i<n;i++) scanf("%d",&a[i]); for(i=0;i<n-1;i++) { for(j=0;j<n-1-i;j++) { if(a[j+1] < a[j]) { temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; } } } printf("\nThe sorted array is\n"); for(i=0;i<n;i++) printf("%d\t",a[i]); printf("\nEnter the element to be found"); scanf("%d",&key); flag=binary(a,key); break; default: exit(0);

} if(flag==0) printf("\nThe element is not found"); else printf("\nElement is at position %d",flag); end=clock(); printf("\nThe runtime calculated using clock function is %f sec",(end-start)/CLK_TCK); getch(); } int binary(int a[10],int key) { int low,high,m; low=0; high=n-1; while(low<=high) { m=(low+high)/2; if(key==a[m]) return m; else if(key <a[m]) high=m-1; else low=m+1; } return (0); }

OUTPUT
Enter the no of elements of the array 6 Is the array sorted?Press 1 for sorted array and pres 0 for unsorted array 1 Enter the elements of the array 7 4 6 8 9 11 Enter the element to be found 2 The element is not found The runtime calculated using clock function is 13.736264 sec

You might also like