Thursday, October 21, 2010

/*Bubble Sort and Binary Search*/

/*Bubble Sort and Binary Search*/
main()
{
int a[10],n,i,ch,ele,pos;
clrscr();
printf("Enter the size of array");
scanf("%d",&n);
printf("Enter %d elements",n);
for(i=0;i
scanf("%d",&a[i]);
printf("Elements before Sort\n");
for(i=0;i
printf(" %d ",a[i]);
bubble(a,n);
printf("\nElements after Sort\n");
for(i=0;i
printf(" %d ",a[i]);
while(1)
{
printf("\n1.SEARCH\n2.EXIT\n");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("Enter the element you want to search");
scanf("%d",&ele);
pos=search(a,n,ele);
if(pos==0)
printf("Element not found in the list");
else
printf("Element is at position %d",pos);
break;
case 2: exit();
}
}
}
bubble(int a[],int n)
{
int i,j;
for(i=0;i
for(j=0;j
if(a[j]>a[j+1])
{
a[j]=a[j]+a[j+1];
a[j+1]=a[j]-a[j+1];
a[j]=a[j]-a[j+1];
}
}
search(int a[],int n,int ele)
{
int low,high,mid;
low=0;high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if(a[mid]==ele)
return mid+1;
else if(a[mid]
low=mid+1;
else
high=mid-1;
}
return 0;
}

No comments:

Post a Comment