Search code examples
carraysmaxfunction-definition

All max elements and their postition of array


So, for example, I have array: [1, 4, 9, 3, 9]

I need to find all max elements [9, 9] and their index [2, 4]

How can I do this? In C language

int i, pom, max;
max=*gradovi;
for(i=0;i<n;i++) {
  if(*(gradovi+i)>max) {
    max=*(gradovi+i);
    pom=i;
  }
  if(*(gradovi+i)==max) {
    pom=i;
  }
}
return pom;

I need postions of all max elemenents, but this print just last


Solution

  • In any case you need a container that will store the indices of the elements with the maximum value.

    You can allocate memory dynamically for such a container.

    Here is a demonstrative program.

    #include <stdio.h>
    #include <stdlib.h>
    
    size_t max_elements( const int a[], size_t n, size_t **result )
    {
        *result = NULL;
        size_t count = 0;
    
        if ( n != 0 )
        {
            size_t max_i = 0;
            count = 1;
    
            for ( size_t i = 1; i < n; i++ )
            {
                if ( a[max_i] < a[i] )
                {
                    max_i = i;
                    count = 1;
                }
                else if ( !( a[i] < a[max_i] ) )
                {
                    ++count;
                }
            }
    
            *result = malloc( count * sizeof( size_t ) );
    
            if ( *result != NULL )
            {
                for ( size_t i = max_i, j = 0; i < n && j < count; i++ )
                {
                    if ( !( a[i] < a[max_i ] ) ) ( *result )[j++] = i;
                }               
            }           
        }
    
        return count;
    }
    
    int main(void) 
    {
        int a[] = { 1, 4, 9, 3, 9 };
        const size_t N = sizeof( a ) / sizeof( *a );
    
        size_t *result = NULL;
    
        size_t count = max_elements( a, N, &result );
    
        for ( size_t i = 0; i < count; i++ )
        {
            printf( "%zu: %d, ", result[i], a[result[i]] );
        }
    
        putchar( '\n' );
    
        free( result );
    
        return 0;
    }
    

    Its output is

    2: 9, 4: 9,
    

    If the returned value from the function is not equal to 0 but the pointer result was set to NULL then it means that there was a memory allocation error. You can check such a situation.