问题 : 整理数组
时间限制: 1 Sec 内存限制: 128 MB
提交: 4088 解决: 829
[提交][状态][讨论版]
题目描述
给定一个数组input,如果数组长度n为奇数,则将数组中最大的元素放到output数组最中间的位置,如果数组长度n为偶数,则将数组中最大的元素放到output数组中间两个位置偏右的位置,然后将其余的数按从大到小的顺序,依次一左一右放置到前一组数的两边。
请用函数实现上述功能,要求函数原型为:void ResetArray(int input[], int n, int output[]);
例如:
input[] = {3, 6, 1, 9, 7} output[] = {3, 7, 9, 6, 1};
input[] = {3, 6, 1, 9, 7, 8} output[] = {1, 6, 8, 9, 7, 3}
代码实现
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
void ResetArray(int input[], int n, int output[]);
int main() {
int n = 0;
scanf("%d", &n);
int* arr = (int*)malloc(n * sizeof(int));
int* arr2 = (int*)malloc(n * sizeof(int));
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
ResetArray(arr, n, arr2);
int i = 0;
for (; i < n - 1; i++) {
printf("%d,", arr2[i]);
}
printf("%d\n", arr2[i]);
return 0;
}
void ResetArray(int input[], int n, int output[]){
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++) {
if (input[j] < input[j + 1]) {
int tmp = input[j];
input[j] = input[j + 1];
input[j + 1] = tmp;
}
}
}
output[n/2] = input[0];
int a = 1;
int k = 1;
while (k < n)
{
output[n / 2 - a] = input[k++];
a++;
output[n / 2 + a - 1] = input[k++];
}
}