给定一个数组 input[] ,如果数组长度 n 为奇数,则将数组中最大的元素放到 output[] 数组最中间的位置,如果数组长度 n 为偶数,则将数组中最大的元素放到 output[] 数组中间两个位置偏右的那个位置上,然后再按从大到小的顺序,依次在第一个位置的两边,按照一左一右的顺序,依次存放剩下的数。
例如:input[] = {3, 6, 1, 9, 7} output[] = {3, 7, 9, 6,
input[] = {3, 6, 1, 9, 7, 8} output[] = {1, 6, 8, 9, 7, 3}
函数接口 void sort(int input[], int n, int output[])
解析:
#include
"iostream"
using namespace std;
void
bubblesort(int
data[],
int
n)
{
int
temp =
0;
for
(int
i =
0; i < n; i++ )
{
for
(int
j = i +
1; j < n; j++)
{
if
(data[i] < data[j])
{
temp = data[i];
data[i] = data[j];
data[j] = temp;
}
}
}
}
void
sort(int
input[],
int
n,
int
output[])
{
int
*sort_input =
new
int[n];
for
(int
i =
0; i < n; i++)
{
sort_input[i] = input[i];
}
bubblesort(sort_input, n);
if
(1
== n %
2)
{
int
mid = n /
2;
int
k =
0;
output[mid] = sort_input[k++];
for
(int
j =
1; j <= n /
2; j++)
{
output[mid - j] = sort_input[k++];
output[mid + j] = sort_input[k++];
}
}
else
{
int
mid = n /
2;
int
k =
0;
output[mid] = sort_input[k++];
for
(int
j =
1; j < n /
2; j++)
{
output[mid - j] = sort_input[k++];
output[mid + j] = sort_input[k++];
}
output[0] = sort_input[k++];
}
delete sort_input;
}
void
main()
{
int
input1[] = {3,
6,
1,
9,
7};
int
output1[5];
memset(output1,
0,
5
* sizeof(int));
int
input2[] = {3,
6,
1,
9,
7,
8} ;
int
output2[6];
memset(output2,
0,
6
* sizeof(int));
sort(input1,
5, output1);
sort(input2,
6, output2);
for
(int
k =
0; k <
5; k++)
printf("%d", output1[k]);
printf("\n");
for
(k =
0; k <
6; k++)
printf("%d", output2[k]);
printf("\n");
}Ï