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;
}
}
华为机试---数组按规则排列
最新推荐文章于 2023-10-26 19:48:39 发布