找到一个数组中第二小值 O(n)


void swap(int *a, int *b)
{
	int t = *a;
	*a = *b;
	*b = t;
}
int second_min(int *arr, int len)
{
	int min_index = 0;
	for (int i = 1; i < len; i++)
		if (arr[i] < arr[min_index])
			min_index = i;
	swap(&arr[0], &arr[min_index]);

	min_index = 1;
	for (int i = 2; i < len; i++)
		if (arr[i] < arr[min_index])
			min_index = i;

	return arr[min_index];
}

#include <stdio.h>
int main()
{
	int a[100] = { 0 };
	printf("请输入数组长度(不大于100): ");
	int len;
	scanf("%d", &len);
	for (int i = 0; i < len; i++)
	{
		printf("请输入数组第%d个元素:", i);
		scanf("%d", &a[i]);
	}

	printf("第二小值是%d\n", second_min(a,len));

	return 0;
}
posted @ 2022-04-19 18:17  enbug  阅读(32)  评论(0编辑  收藏  举报