来源twc829,题目描述:
给定一个数组input[] ,如果数组长度n为奇数,则将数组中最大的元素放到 output[] 数组最中间的位置,如果数组长度n为偶数,则将数组中最大的元素放到 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}
代码:
# include <iostream>
# include <stdlib.h>
int * get(int *input, int lenth)
{
// 先排序
for (int i = lenth - 1; i > 0; i--)
for (int j = 0; j < i; j++)
{
if (input[j] < input[j+1])
{
int temp = input[j];
input[j] = input[j+1];
input[j + 1] = temp;
}
}
//for (int i = 0; i < lenth; i++)
// std::cout << input[i] << " ";
//std::cout << std::endl;
int *output = (int *)malloc(sizeof(int)* lenth);
// 方法1:观察数据,先放左边的,即原数组从右往左隔两个数,再放中位数以及右边的,即原数组从左往右隔两个,注意奇偶数个数不同,开始位置不同
//if (lenth % 2 == 0)
//{
// int j = 0;
// for (int i = lenth - 1; i > 0; i = i - 2, j++)
// output[j] = input[i];
// for (int i = 0; i < lenth; i = i + 2, j++)
// output[j] = input[i];
//}
//else
//{
// int j = 0;
// for (int i = lenth - 2; i > 0; i = i - 2, j++)
// output[j] = input[i];
// for (int i = 0; i < lenth; i = i + 2, j++)
// output[j] = input[i];
//}
// 方法二,找出中位数(即原数组第一个),放到新数组中间,然后将原数组两个两个的一起处理,在中位数左边和右边分别放置。注意,奇偶个数不同时,处理方式不一样
int posi;
if (lenth % 2 == 1)
{
posi = (lenth - 1) / 2;
output[posi] = input[0];
for (int i = 1; i <= posi; i++) // posi:是中位数,也是成对处理的数据对数
{
output[posi - i] = input[2 * i - 1];
output[posi + i] = input[2 * i];
}
}
else
{
posi = lenth / 2;
output[posi] = input[0];
for (int i = 1; i <= posi - 1; i++)
{
output[posi - i] = input[2 * i - 1];
output[posi + i] = input[2 * i];
}
output[0] = input[lenth - 1]; // 偶数个数时,右侧中位数单独处理了,所以,最后一个数没有成对的处理
}
for (int i = 0; i < lenth; i++)
std::cout << output[i] << " ";
return input;
}
int main()
{
int input[5] = { 5, 3, 6, 8, 1};
// int input[6] = { 5, 3, 6, 8, 1 };
int lenth = sizeof(input) / sizeof(int);
int *output = get(input, lenth);
std::cout << "ok";
}
思想:先排序,后按照奇偶个数不同,单独处理。一左一右放,可以考虑到一次放一对。