一道java笔试题
输入一串用空格隔开的数字串,对于数字串的奇数位按升序排序,偶数位按降序排序.
示例输入:
4 6 2 3 6 7 8 1
处理过程:
奇数位:4 2 6 8 升序排序结果: 2 4 6 8
偶数位:6 3 7 1 降序排序结果: 7 6 3 1
结果输出:2 7 4 6 6 3 8 1
demo:
import java.util.*;public class Main {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
String inStr = scan.nextLine();
scan.close();
String[] strs = inStr.split(" ");
int N = strs.length;
int[] inNums = new int[N];
for (int i = 0; i < N; i++) {
inNums[i] = Integer.parseInt(strs[i]);
// System.out.println(strs[i]);
}
int tmp = 0;
//奇数位升序
for (int i = 0; i < N - 1; i = i + 2) {
for (int j = i; j < N - 1; j = j + 2) {
if (inNums[i] > inNums[j]) {
tmp = inNums[i];
inNums[i] = inNums[j];
inNums[j] = tmp;
}
}
}
//偶数位降序
for (int i = 1; i < N - 1; i = i + 2) {
for (int j = i; j < N - 1; j = j + 2) {
if (inNums[i] < inNums[j]) {
tmp = inNums[i];
inNums[i] = inNums[j];
inNums[j] = tmp;
}
}
}
for (int i = 0; i < N; i++) {
System.out.print(inNums[i]);
System.out.print(" ");
}
}
}
以上是 一道java笔试题 的全部内容, 来源链接: utcz.com/z/389958.html