获取数组的第一大值和第二大值

#include 
#include 
#include 

int arry[10] = {8, 2, 4, 6, 8, 3, 1};

int main()
{
	int n = 0, i = 0 ,j = 0;
	int max_value = 0, max_value_index = 0;
	int second_max_value = 0, second_max_value_index = 0;

	//数组中没有相同的元素
	max_value = arry[0];
	max_value_index = 0;
	second_max_value = arry[0];
	second_max_value_index = 0;
	for (n = 0; n < sizeof(arry)/sizeof(arry[0]); n++) {
		if (arry[n] > max_value) {
			second_max_value = max_value;
            second_max_value_index = max_value_index;
			max_value = arry[n];
			max_value_index = n;
		} else {
			if (arry[n] > second_max_value) {
				second_max_value = arry[n];
				second_max_value_index = n;
			}
		}
	}

printf("===================数组中MEI有相同的元素========================\n");
printf("max_value:%d, max_value_index:%d\n", max_value, max_value_index);
printf("second_max_value:%d, second_max_value_index:%d\n", second_max_value, second_max_value_index);


	//数组中有相同的元素
	max_value = -10;//初始化一个最小的值
	max_value_index = 0;
	for (i = 0; i < sizeof(arry)/sizeof(arry[0]); i++) {
		if (arry[i] > max_value) {
			max_value = arry[i];
			max_value_index = i;
		}
	}

	second_max_value = -10;//初始化一个最小的值
	second_max_value_index = 0;
	for (j = 0; j < sizeof(arry)/sizeof(arry[0]); j++) {
		if (arry[j] > second_max_value && arry[j] < max_value) {
			second_max_value = arry[j];
			second_max_value_index = j;
		}
	}

printf("===================数组中有相同的元素========================\n");
printf("max_value:%d, max_value_index:%d\n", max_value, max_value_index);
printf("second_max_value:%d, second_max_value_index:%d\n", second_max_value, second_max_value_index);

	return 0;
}




===================数组中MEI有相同的元素========================
max_value:8, max_value_index:0
second_max_value:8, second_max_value_index:0
===================数组中有相同的元素========================
max_value:8, max_value_index:0
second_max_value:6, second_max_value_index:3



 

你可能感兴趣的:(获取数组的第一大值和第二大值)