/*
给定一个数组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}
函数接口 void sorts(int input[], int n, int output[]
*/
#include<cstdio>
#include<cstring>
#include<iostream>
#include<math.h>
using namespace std;
/*
关于compare 函数:1 参数为const类型的空指针
2 a-b 时为从小到大排序 b-a时是从大到小排序
*/
int compare(const void *a,const void *b)
{
return *(int *)b-*(int *)a;
}
void sorts(int input[], int n, int output[])
{
int i;
int j;
qsort(input, n,sizeof(input[0]),compare);
if(n%2 == 1) //最大值放到中间位置,数组元素个数为奇数时的情况
{
output[(n-1)/2]= input[0];
/*中间放置最大值input[0] 左边放置input[1,3,5...]*/
j=1;
for(i=(n-1)/2-1;i>=0;i--) //先放置前一部分
{
output[i] = input[j];
j+=2;
}
/*中间放置最大值input[0] 右边边放置input[2,4,6...]*/
j=2;
for(i=(n-1)/2+1;i<n;i++)
{
output[i] = input[j];
j+=2;
}
}
else if(n%2 == 0) //最大值放到中间位置,数组元素个数为偶数时的情况
{
/*注意:n为数组元素个数(偶数),n-1为数组最大下标为奇数,(n-1+1)/2为中间偏右的位置*/
output[(n)/2]= input[0];
j=1;
for(i=(n)/2-1;i>=0;i--)
{
output[i] = input[j];
j+=2;
}
j=2;
for(i=(n)/2+1;i<n;i++)
{
output[i] = input[j];
j+=2;
}
}
}
int main(/*int argc, char **argv*/)
{
int input[6]={3,6,1,9,7,8};
int output[6]={0};
int i;
sorts(input, 6, output);
for(i=0;i<6;i++)
printf("%d ",output[i]);
return 0;
}
华为:给定一个数组input[],如果数组长度n为奇数,则将数组中最大的元素放到 output[]数组最中间的位置,如果数组长度n为偶数。。
最新推荐文章于 2023-06-25 20:49:37 发布