Finding 2 of the same elements in array

S

slickn_sly

int find_index_of_min( float num[], int arraySize )
{
int index, min;

min = 0;
for( index = 1; index < arraySize; index++ )
{
if( num[min] > num[index] )
{
min = index;
}
}

return min;
}


How can i modify this code so that if an array contains 2 or more of
the exact elements which are the smallest, it will return the index
for both of those elements?
 
M

Michael Mair

slickn_sly said:
int find_index_of_min( float num[], int arraySize )
{
int index, min;

min = 0;
for( index = 1; index < arraySize; index++ )
{
if( num[min] > num[index] )
{
min = index;
}
}

return min;
}


How can i modify this code so that if an array contains 2 or more of
the exact elements which are the smallest, it will return the index
for both of those elements?

Sounds like homework. Maybe you should write the modifications
as far as you can get and come back with that code.


-Michael
 
E

Eric Sosman

slickn_sly said:
int find_index_of_min( float num[], int arraySize )
{
int index, min;

min = 0;
for( index = 1; index < arraySize; index++ )
{
if( num[min] > num[index] )
{
min = index;
}
}

return min;
}


How can i modify this code so that if an array contains 2 or more of
the exact elements which are the smallest, it will return the index
for both of those elements?

There are 2**arraySize - 1 possible return values,
so if you happen to know that arraySize is small you could
return a bit map of the positions holding the minimum.

For larger arraySize, you would need to create an array
to hold all the indices and return the array (you'd also need
a way to tell the caller how big the array is; perhaps you'd
stick a -1 after all the actual indices).

A different approach would be to break the problem up
into multiple calls. Use the function as it stands to find
the lowest-indexed occurrence of the minimum, and write a
second function to find the next occurrence of that same
value:

int find_next(float num[], int arraySize, int min) {
int pos;
for (pos = min; ++pos < arraySize; ) {
if (num[pos] == num[min])
return pos;
}
return -1; /* no more minima */
}

The caller could use the two functions to find the first
minimum and all its duplicates, something like

int min;
min = find_index_of_min(array, size);
printf ("Minimum %g appears at %d", array[min], min);
while ((min = find_next(array, size, min)) >= 0)
printf (" and %d", min);
printf ("\n");
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,053
Latest member
billing-software

Latest Threads

Top