I am trying to make an array where odd numbers are sorted in order using Bubble sort algorithm on the left side of the array, and even numbers are sorted in order on the right side of the array.
The output should be like this:
int[] a = {1,2,3,4,5,6,7,8,9,10}
output: 1 3 5 7 9 2 4 6 8 10
The first split between even and odd numbers works, and also the sorting of the odd numbers, but the even numbers are not sorted, and I don't know why.
My Code:
public class ObligOppgave4 {
public static void main(String[] args) {
int[] a = {1,2,3,4,5,6,7,8,9,10};
sortEvenAndOdd(a);
bubbleSortOdd(a);
bubbleSortEven(a);
print(a);
}
public static void sortEvenAndOdd(int[] a) {
int l = a.length;
int v = 0, h = l - 1;
if (a.length == 0) return;
while (v <= h) {
if (((a[v] % 2) == 0) && !((a[h] % 2) == 0)) {
change(a, v++, h--);
} else if ((a[v] % 2) == 0) {
h--;
} else if (!((a[h] % 2) == 0)) {
v++;
} else if (!((a[v] % 2) == 0) && ((a[h] % 2) == 0)) {
v++;
h--;
}
}
}
public static void bubbleSortOdd(int[] a) {
for (int n = 0; n < a.length; n++) {
for (int i = 1; i < n && a[i] % 2 != 0; i++) {
if (a[i - 1] > a[i]) {
change(a, i - 1, i);
}
}
}
}
public static void bubbleSortEven(int[] a){
for (int n = 0; n < a.length; n++) {
for (int i = 1; i < n && a[i] % 2 == 0; i++) {
if (a[i - 1] > a[i]) {
change(a, i ,i);
}
}
}
}
public static void change(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public static void print(int[] a) {
for(int i = 0; i < a.length; i++)
System.out.print(a[i] + " ");
System.out.println();
}
}