比较次数: N-1
#include
#include
#include
#define MAX_LENGTH 100
/*Show usage*/
void usage(char * prog)
{
printf("%s Usage:\n", prog);
printf("%s \n", prog);
}
/*Try to find the max one in the list and return it*/
int find_max(int * list, int n)
{
int i = 1, max;
max = list[0];
while(i < n)
{
if(max < list[i])
{
max = list[i];
}
i ++;
}
return max;
}
/*Generate and initialize the list*/
int * generate_list(int count)
{
int i;
int * list;
list = (int *)malloc(count*sizeof(int));
if(list == NULL)
{
perror("malloc");
return NULL;
}
/*Initialize the list with integers less than 100*/
srandom((unsigned int)time(NULL));
for (i = 0; i < count ; i ++)
list[i] = random()%100;
return list;
}
int main(int argc, char * argv[])
{
int length, i;
int * list = NULL;
int max;
/*Deal with the arguments*/
if(argc != 2)
{
usage(argv[0]);
exit(127);
}
length = atoi(argv[1]);
if(!length || length > MAX_LENGTH)
{
usage(argv[0]);
exit(129);
}
list = generate_list(length);
if(list == NULL)
exit(128);
else
{
for(i = 0; i < length; i ++)
printf("%d ", list[i]);
printf("\n");
max = find_max(list, length);
printf("The max one is: %d\n", max);
}
free(list);
return 1;
}
阅读(1539) | 评论(0) | 转发(0) |