Simple “maximum value in array” and complexity calculations

前端 未结 4 1084
眼角桃花
眼角桃花 2021-02-20 07:15

I\'m pretty new to this stuff and I need your help.

I should build an efficient simple algorithm which returns the maximum value in an array with size of n which contain

4条回答
  •  不知归路
    2021-02-20 07:42

    The algorithm works like this, first you select a number (in this case i select the first number of the array and pretend it is the max, then i compare it to the next number and if it is larger I take that as the new max, until i finish searching in the array), the next code is in C:

    #include 
    #define SIZE 100
    
    typedef struct{
        int val;
        int loc;
    } find;
    
    /* Functions declaration (Prototype) */
    find maxFinder( int * const a );
    
    int main( void )
    {
        int response[ SIZE ]=
           { 1, 3, 5, 7,  8, 9, 0, 10, 65, 100,
             1, 3, 5, 7,  8, 9, 0, 10, 65, 100,
             1, 3, 5, 7,  8, 9, 0, 10, 65, 100,
             1, 3, 5, 7,  8, 9, 0, 10, 65, 100,
             1, 3, 5, 7,  8, 9, 0, 10, 65, 100,
             1, 3, 5, 7,  8, 9, 0, 10, 65, 100,
             1, 3, 5, 7,  8, 9, 0, 10, 65, 100,
             1, 3, 5, 7,  8, 9, 0, 10, 65, 100,
             1, 3, 5, 7,  8, 9, 0, 10, 65, 100,
             1, 3, 5, 7,  8, 9, 0, 10, 65, 100 };
    
        printf( "The max number is %d located in the index %d.\n", maxFinder( response ).val, maxFinder( response ).loc );
        return 0;
    }
    
     find maxFinder( int * const a )
     {
        /* Local Variables initialization & declaration */
        int i;
        find result;
    
        result.loc = 0;
        result.val = *( a + 0 );
    
        for( i = 1; i < SIZE; i++ ){
            if ( result.val < *( a + i ) ){
                result.loc = i;
                result.val = *( a + i );
            }
        }
        return result;
     }
    

提交回复
热议问题