华为机试---数组按规则排列

package huawei;

import java.util.Scanner;

/**
 * 给定一个数组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}
 *  
 *  难点:处理奇数偶数下标的排序,采用for循环中i的分开处理
 * @author USER
 *
 */
public class Sort {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		String string = in.nextLine();
		String[] str = string.split(" ");
		int[] a = new int[str.length];
		for (int i = 0; i < str.length; i++) {	//将字符串数组转化为整数数组
			a[i] = Integer.parseInt(str[i]);
		}
		int[] result = sort(a);
		for (int i = 0; i < result.length; i++) {
			System.out.print(result[i]+" ");
		}
	}

	private static int[] sort(int[] data) {
		// TODO Auto-generated method stub
		int[] temp = data;
		for (int i = 0; i < temp.length-1; i++) {	//实现数组的排序
			for (int j = i+1; j < temp.length; j++) {
				if (temp[i] < temp[j]) {
					int t = temp[i];
					temp[i] = temp[j];
					temp[j] = t;
				}
			}
		}
		
		int[] output = new int[data.length];
		int len = output.length;
		output[len/2] = temp[0];
		int left = temp.length/2-1;
		int right = temp.length/2+1;
		for (int i = 1; i < len;) {//注意此处的奇数偶数的处理
			if (left >= 0) {
				output[left] = temp[i];
				left--;
				i++;
			}
			if (right < len) {
				output[right] = temp[i];
				right++;
				i++;
			}
		}
		return output;
	}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值