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");