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. It is very readable and has lower complexity of O(N log N).What you can do is write a recursive function like so:
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] + " ");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.