快速找出一個數組中的最大數、第二大數
阿新 • • 發佈:2018-11-27
#include <stdio.h>
int main()
{
int a[] = {12, 159, 8, 1, 165, 122, 56, 99, 165};
int len = sizeof(a)/sizeof(a[0]);
int rank1 = a[0], rank2 = a[1];
int i, tmp;
if (rank2 > rank1)
{
tmp =rank1;
rank1 = rank2;
rank2 = tmp;
}
else if (rank2 == rank1)
rank2 = -32767;
for (i = 2;i < len; i++)
{
if((a[i] > rank2) && (a[i] < rank1))
{
rank2 = a[i];
}
else if (a[i] > rank1)
{
rank2 = rank1;
rank1 = a[i];
}
}
printf("rank1 = %d,rank2 = %d\n", rank1, rank2);
return 0;
}