算法是这样工作的,首先你选择一个数字(在这种情况下,我选择数组的第一个数字并假装它是最大值,然后我将它与下一个数字进行比较,如果它更大,我将它作为新的最大值,直到我在数组中完成搜索),下一个代码在 C 中:
#include <stdio.h>
#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;
}