Michiel Rapati-Kekkonen wrote:
bsearch finds me only the first occurrence of something I'm looking for,
but I would like to know the place in the list where it is found.
The index of it's place in the array.
So that I can check if there are more to find on the next places.
I need to find all occurences.
Maybe anyone of you know even a better way?
I do believe your approach is the best method for searching an
existing array. Once the array is sorted, use function bsearch
to search for the key value. If it is found, then search the
elements adjacent to the key element for duplicates.
Example using a integer array;
#include <stdio.h>
#include <stdlib.h>
#define SZ 6
void printarray(int *iia,const char *s);
int cmp(const void *v1, const void *v2);
void printfindmore(int *ia, int elemnr);
int main(void)
{
int key, *ip,elem,iarray[SZ] = {3,5,1,3,4,3};
printarray(iarray,"Unsorted");
qsort(iarray,SZ,sizeof *iarray,cmp);
printarray(iarray,"\nSorted Assending");
key = 3;
printf("\n\tSearching for value: %d\n",key);
ip = bsearch(&key,iarray,SZ,sizeof *iarray,cmp);
if(!ip)
printf("The value: %d was not found\n",key);
else
{
elem = ip - iarray;
printf("The value: %d was found at element %d\n",
key, elem);
printfindmore(iarray,elem);
}
return 0;
}
void printarray(int *ia,const char *s)
{
int i;
printf("\t%s\n",s);
for(i = 0; i < SZ; i++)
printf("array[%d] = %d\n",i,ia[i]);
return;
}
int cmp(const void *v1, const void *v2)
{
const int *i1 = v1;
const int *i2 = v2;
return (*i1 < *i2)?-1:(*i1 != *i2);
}
void printfindmore(int *ia, int elemnr)
{
int i;
for(i = elemnr-1; i >= 0;i--)
{
if(ia[i] != ia[elemnr]) break;
printf("Value %d was also found at element %d\n",
ia[elemnr],i);
}
for(i = elemnr+1; i < SZ; i++)
{
if(ia[i] != ia[elemnr]) break;
printf("Value %d was also found at element %d\n",
ia[elemnr],i);
}
return;
}
--
Al Bowers
Tampa, Fl USA
mailto:
xa******@myrapidsys.com (remove the x to send email)
http://www.geocities.com/abowers822/