[英]How do you sort odd and even array numbers in descending and ascending order?
I need help to sort numbers in an array in ascending and descending order.我需要帮助按升序和降序对数组中的数字进行排序。 Even numbers should be ascending and odd numbers descending.
偶数应该升序,奇数应该降序。
I have managed to sort the number in ascending order but want to do the opposite for the odd numbers.我已经设法按升序对数字进行排序,但想对奇数进行相反的操作。
Actual Results: Both odd and even numbers ascending实际结果:奇数和偶数都升序
Expected Results: Even numbers ascending and odd numbers descending预期结果:偶数递增,奇数递减
System.out.println("\n" + "random numbers generated:");
System.out.println(Arrays.toString(arrayList).replace("[", "").replace("]", "").replace(",", ""));
for (int i = 0; i < arrayList.length; i++) {
for (int j = i+1; j < arrayList.length; j++) {
if(arrayList[i] > arrayList[j]) {
temporaryArray = arrayList[i];
arrayList[i] = arrayList[j];
arrayList[j] = temporaryArray;
}
}
}
System.out.println("\n" + "random numbers arranged:");
int[] arrayTwo = Arrays.copyOf(arrayList, arrayList.length);
for (int i = 0; i < arrayList.length; i++) {
if(arrayTwo[i]%2!=0) {
System.out.print(arrayTwo[i] + " ");
}
}
System.out.print("| ");
for (int i = 0; i < arrayList.length; i++) {
if(arrayTwo[i]%2==0) {
System.out.print(arrayTwo[i] + " ");
}
}
How can I reverse array for odd numbers?如何反转奇数数组?
I would recommend that you:我建议您:
Arrays
library's Arrays.sort()
to simplify your code.Arrays
库的Arrays.sort()
来简化您的代码。 It is very readable and has lower complexity of O(N log N). What you can do is write a recursive function like so:你可以做的是像这样写一个递归的 function :
public static void printOddReversed(int[] array, int index) {
if (index == array.length)
return;
printOddReversed(array, index + 1);
if (array[index] % 2 != 0) {
System.out.print(array[index] + " ");
}
}
and then instead of the second loop, call it like so:然后代替第二个循环,这样称呼它:
printOddReversed(arrayTwo, 0);
A simple way to do that is by using a special comparator:一个简单的方法是使用一个特殊的比较器:
if (a%2 == 0) {
if (b%2 == 0) {
return Integer.compare(a,b);
} else {
return -1;
}
} else {
if (b%2 == 0) {
return 1;
} else {
return Integer.compare(b, a);
}
}
UPDATE: Example更新:示例
int[] arrayList = {959, 321, 658, 3, 506, 165, 560, 582, 199, 533, 178};
for (int i = 0; i < arrayList.length; i++) {
for (int j = i+1; j < arrayList.length; j++) {
if(compare(arrayList[i], arrayList[j]) > 0) {
int temporaryArray = arrayList[i];
arrayList[i] = arrayList[j];
arrayList[j] = temporaryArray;
}
}
}
System.out.println(Arrays.toString(arrayList));
... ...
private static int compare(int a, int b) {
if (a%2 == 0) {
if (b%2 == 0) {
return Integer.compare(a,b);
} else {
return -1;
}
} else {
if (b%2 == 0) {
return 1;
} else {
return Integer.compare(b, a);
}
}
}
I managed to solve this by just reversing我设法通过倒车解决了这个问题
for (int i = arrayList.length-1;i>=0;i--) {
if(arrayTwo[i]%2==0) {
System.out.print(arrayTwo[i] + " ");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.