Archive for the ‘Lab 5’ Category

#include<stdio.h>
#include<stdlib.h>
int c=0;
int binarysearch(int *,int,int);
int binarysearch(int *a,int m,int n)
{

	int l,u,mid;
l=0,u=n-1;
    while(l<=u)
		{
         mid=(l+u)/2;
         if(m==a[mid])
			{
             c=1;
             break;
         }
         else if(m<a[mid])
			{
             u=mid-1;
         }
         else
             l=mid+1;
    }
	return mid;
}
int main()
{

    int *a,i,n,m,pos;

    printf("Enter the size of an array: ");
    scanf("%d",&n);
		a=(int*)malloc(n*sizeof(int));

    printf("Enter the elements in ascending order: ");
    for(i=0;i<n;i++)
		{
         scanf("%d",(a+i));
    }

    printf("Enter the number to be search: ");
    scanf("%d",&m);
		pos=binarysearch(a,m,n);

    
    if(c==0)
         printf("The number is not found.\n");
    else
         printf("The number is found at position %d\n",pos+1);

    return 0;
}
Advertisements
#include<stdio.h>
#include<stdlib.h>
int c=0;
int linearsearch(int *, int,int);
int linearsearch(int *a,int b,int  n)
{
	int i;
for(i=0;i<=n-1;i++)
    {
         if(*(a+i)==b)
	   {
             c=1;
             break;
         }
    }
	return i;

}

int main()
{
	int *a,i,n,m;

    printf("Enter the size of an array: ");
    scanf("%d",&n);
	a=(int*)malloc(n*sizeof(int));

    printf("Enter the elements of the array: ");
    for(i=0;i<=n-1;i++)
    {
         scanf("%d",(a+i));
    }

    printf("Enter the number to be search: ");
    scanf("%d",&m);
	i=0;
	i=linearsearch(a,m,n);
    
    if(c==0)
         printf("The number is not in the list\n");
    else
         printf("The number is found at position %d\n",i+1);

    return 0;
}