(C++) CPP Programs - 15

Friday, December 14, 2007

15. Write a C program to accept N numbers sorted in ascending order and to search for a given number using Binary search. Report success or failure in the form of suitable messages.

/* Binary Search*/

#include

#include

void main()

{

int a[34],first,last,mid,n,key,i,pos=0;

clrscr();

printf("Enter no of digits:\n\a");

scanf("%d",&n);

printf("Enter the elements one by one\n");

for(i=0;i <>

scanf("%d",&a[i]);

printf("The key element to be searched\n");

scanf("%d",&key);

printf("\nArray after sorting\n");

for(i=0;i <>

printf("%4d",a[i]);

first=0;

last=n-1;

while(first < = last)

{

mid=(first+last)/2;

if(a[mid] <>

last=mid-1;

else if(a[mid] > key)

first=mid+1;

else

{

pos=mid;

break;

}

}

if(a[mid]==key)

printf("\n Element found at location %d\n\a",pos);

else

printf("\nElement not found\n\a");

getch();

}

0 comments:

Post a Comment

Chitika

About This Blog

Followers

Blog Archive

  © Blogger template The Professional Template II by Ourblogtemplates.com 2009

Back to TOP