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?
CodePudding user response:
I would recommend that you :
-
- sort all numbers in ascending order,
-
- extract the odd numbers to a second array and
-
- reverse this new array.
Manipulating two different orderings in a same array would prove much more complicated.
On a side note, if you don't have a requirement not to, I'd recommend using the
Arrays
library'sArrays.sort()
to simplify your code. It is very readable and has lower complexity of O(N log N).
- reverse this new array.
Manipulating two different orderings in a same array would prove much more complicated.
On a side note, if you don't have a requirement not to, I'd recommend using the
CodePudding user response:
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 third loop, call it like so:
printOddReversed(arrayTwo, 0);
CodePudding user response:
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);
}
}
}