Intermediate Level
Implement the sortOnlyEvenNumbers method that sorts only the even numbers while keeping odd numbers in their positions.
The input contains an integer array nums and its length size. Your task is to sort only the even numbers in ascending order while keeping all odd numbers in their original positions.
For example, in [5,8,3,2,4], the odd values 5 and 3 stay where they are. Only the even values 8,2,4 are sorted and placed back, so the result is [5,2,3,4,8].
Do not sort the complete array, because odd values must not move.
First collect all even numbers into a separate list. Sort that list in ascending order. Then scan the original array again, and whenever an even position is found, replace it with the next value from the sorted even list.
This keeps odd numbers fixed and changes only the order of even numbers.
Pseudocode:
function sortOnlyEvenNumbers(nums, size):
evens = empty list
for each value in nums:
if value % 2 == 0:
add value to evens
sort evens in ascending order
evenIndex = 0
for i from 0 to size - 1:
if nums[i] % 2 == 0:
nums[i] = evens[evenIndex]
evenIndex++
return nums