All about programming in GNU/LINUX

Improved Linear search code with general function for Search and comparison which can handle any data type…

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void *cmp(void *,void *);
void *lsearch(void * ,void *, int ,int);

int main()
{
int key , n , i;
int *o;
printf(“\nEnter the no.of.Elements: “);
scanf(“%d”,&n);
int arr[n];
for(i=0;i<n;i++)
scanf(“%d”,&arr[i]);
printf(“\nEnter the key to be searched: “);
scanf(“%d”,&key);
o=lsearch(&key,arr,n,sizeof(int));
if(o)
printf(“\nThe address of the base = %u and Address of the  match = %u”,&arr[0],o);
return 0;

}
void *lsearch(void *key,void *base,int n,int size)
{
int i;
for(i=0;i<n;i++)
{
void *elmntadd=(char *)base+(i*size);
if(cmp(key,elmntadd)==0)//why are sending values
{
printf(“Match found at %dth position”,i+1);
return elmntadd;
}

}
printf(“\nMatch not found”);
return NULL;
}//why are we recieving the values are stars
void *cmp(void *key,void *elmntadd)//does the code remains general if this is function is made type specific
{
char *i=key;//how to work without type casting them ???
char *j=elmntadd;
return *i – *j;//Remove star and ask them
}
//How to go about if addresses of pointers are sent from key and Elmntadd;

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s