![]() |
VOOZH | about |
Given an array arr[] of positive integers. The task is to sort them so that the first part of the array contains odd numbers sorted in descending order, and the rest of the portion contains even numbers sorted in ascending order.
Examples:
Input: arr[] = [1, 2, 3, 5, 4, 7, 10]
Output: [7, 5, 3, 1, 2, 4, 10]
Explanation: 7, 5, 3, 1 are odds in descending order and 2, 4, 10 are evens in ascending order.Input: arr[] = [0, 4, 5, 3, 7, 2, 1]
Output: [7, 5, 3, 1, 0, 2, 4]
Explanation: 7, 5, 3, 1 are odds in descending order and 0, 2, 4 are evens in ascending order.Input: arr[] = [6, 9, 2, 8, 3, 7]
Output: [9, 7, 3, 2, 6, 8]
Explanation: 9, 7, 3 are odds in descending order and 2, 6, 8 are evens in ascending order.
Table of Content
The idea is to first separate all odd and even numbers into two different arrays. Then, we sort the odd numbers in descending order and the even numbers in ascending order. Finally, we reconstruct the original array by placing all sorted odd numbers first, followed by the sorted even numbers.
7 5 3 1 2 4 10
The idea is to partition the array such that all odd numbers are placed before the even numbers. Once partitioned, we can independently sort the odd and even parts: odds in descending and evens in ascending order. This avoids using extra space and gives an efficient in-place solution.
Steps to implement the above idea:
7 5 3 1 2 4 10
The idea is to utilize the fact that negative odd numbers will be treated as smaller in ascending sort. So, we convert all odd elements to negative, making larger odd values more negative (e.g., 7 becomes -7). During sorting, these more negative values (i.e., originally bigger odds) are pushed further to the left, achieving descending order for odds. After sorting, we revert negative numbers back to positive, placing odds in descending order followed by evens in ascending order.
Note: This approach fails when the array already contains negative values, as it cannot distinguish between original and transformed negatives, leading to incorrect results.
7 5 3 1 2 4 10
The idea is to leverage the inbuilt sort function with a custom comparator to sort the array according to the desired condition. The logic for the comparator is based on how two elements compare under three distinct cases:
- If both elements are even, they should be arranged in ascending order, so the smaller even number comes first.
- If both elements are odd, they should be arranged in descending order, meaning the larger odd number should appear earlier.
- If one element is odd and the other is even, the odd number must come before the even number to maintain the required order.
7 5 3 1 2 4 10