Below is the code in image where i have sorted array in ascending order but i am unable to sort only odd numbers, leaving even number at their original place like below [5, 8, 6, 3, 4] => [3, 8, 6, 5, 4]
CodePudding user response:
The key aspect you need to consider is that to ignore even numbers in array and apply your sorting algorithm at odd numbers only. Here's the implementing using bubble sort:
public static void main(String[] args) {
int[] a = {5, 8, 6, 3, 4};
int i, j, n=a.length;
for(i=0; i < n; i ) {
if (a[i]%2 != 0) {
int toPlace = i;
for(j=i 1; j < n; j ) {
if (a[j]%2!=0 && a[i] > a[j]) {
toPlace = j;
}
}
int temp = a[toPlace];
a[toPlace] = a[i];
a[i] = temp;
}
}
for(i=0; i<n; i ) {
System.out.println(a[i]);
}
}
PS: Try building on this intuition for nlogn sorting.