I want to sort the odd numbers using insertion sort in a given array and not touch the even numbers but the even numbers' position will be changing I don't want them to stay between odd numbers
EX:
int arr[] = {1,4,5,2,7,6,3,9,0}
The output should be = {1,3,5,7,9,4,2,6,0}
This is my code where I wrote the insertion code but I couldn't figure out the sorting of only the odd part of the problem
How can I sort odd numbers on the left side in ascending order while putting all the even numbers on the right side without sorting?
public void InsertionOdd(int[] a) {
for (int i = 1; i < a.length; i ) {
int key = a[i];
int j = i - 1;
while(j >= 0 && a[j] > key) {
a[j 1] = a[j];
j = j - 1;
}
a[j 1] = key;
}
for (int i = 0; i < a.length; i ) {
System.out.print(a[i] " ");
}
}
CodePudding user response:
You need to change two things:
- add a validation after assigning the value to the key variable
int key = a[i]; if( key % 2 == 1)
- make sure to move the element selected to the left if the key is bigger than the a[j] or if the a[j] is a even number :
while (j >= 0 && (a[j] > key || a[j]% 2 == 0))
And now the code should work.