华为机试——02一左一右的顺序排序数

/*
2、给定一个数组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 sort(int input[], int n, int output[])
*/

#include <iostream>
using namespace std;

void sort(int input[], int len, int output[])
{
	if(len == 0)
		return;
	int temp = 0;
	
	//sort.
	for(int i = 0;i < len-1;i++)
	{
		for(int j = i;j < len;j++)
		{
			if(input[j] > input[i])
			{
				temp = input[j];
				input[j] = input[i];
				input[i] = temp;
			}
		}
	}
	//store into output.
	int left = len/2- 1;
	int right = len/2;
	for(int k = 0;k < len;k++)
	{
		if(k%2 == 0)
			output[right++] = input[k];		
		else
			output[left--] = input[k];
	}
	for(left = 0;left< len;left++)
		cout << output[left] << " ";
	cout << endl;
}

int main()
{
	int n1 = 5;
	int input1[6] = {3,6,1,9,7};
	int output1[6];
	sort(input1,n1,output1);
	//cout << output1 << endl;
	
	int n2 = 6;
	int input2[7] = {3,6,1,9,7,8};
	int output2[7];
	sort(input2,n2,output2);
	//cout << output2 << endl;
	
	return 0;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值