This question requires writing a program to first exchange the minimum value of a series of input integers with the first number, then exchange the maximum value with the last number, and finally output the exchanged sequence.
Note: The question ensures that the maximum and minimum values are unique.
Input format:
The input gives a positive integer N (≤10) in the first line, and N integers in the second line, separated by spaces.
Output format:
Print the swapped sequence sequentially on a line, with each integer followed by a space.
Input example:
5
8 2 5 1 4
Output sample:
1 2 5 4 8
Code length limit
16 KB
time limit
400 ms
memory limit
64 MB
#include <stdio.h>
int arrmin(int *arr, int length)
{
int m = arr[0];
for (size_t i = 0; i < length; i++)
{
if (arr[i] < m)
{
m = arr[i];
}
}
return m;
}
int arrmax(int *arr, int length)
{
int m = arr[0];
for (size_t i = 0; i < length; i++)
{
if (arr[i] > m)
{
m = arr[i];
}
}
return m;
}
void inputarr(int *arr)
{
int num, i;
char ch;
i = 0;
do
{
scanf("%d", &num);
ch = getchar();
arr[i] = num;
i++;
} while (ch != '\n');
}
int printarr(int *arr, int length)
{
if (sizeof(arr) == 0)
{
return 0;
}
size_t i;
for (i = 0; i < length; i++)
{
printf("%d%c", arr[i], 32);
}
putchar(' \n');
return 1;
}
int main()
{
// 输入样例 8 2 5 1 4
// 最小值与第一个数交换 1 2 5 8 4
// 最大值与最后一个数交换 1 2 5 4 8
// 预期结果 1 2 5 4 8
int n, min, max;
scanf("%d", &n);
int arr[n];
inputarr(arr);
min = arrmin(arr, n);
max = arrmax(arr, n);
for (size_t i = 0; i < n; i++)
{
if (arr[i] == min)
{
arr[i] = arr[0]; // 最小值与第一个数值交换
arr[0] = min; // 第一个数值与最小值交换
}
}
for (size_t i = 0; i < n; i++)
{
if (arr[i] == max)
{
arr[i] = arr[n - 1]; // 最大值与最后一个数交换
arr[n - 1] = max; // 最后一个值与最大值交换
}
}
printarr(arr, n);
return 0;
}