Sort all even numbers in ascending order and then sort all odd numbers in descending order | C ++ implementation of the approach ; Utility function to print the contents of the array ; To do two way sort . Make comparator function for the inbuilt sort function of c ++ such that odd numbers are placed before even in descending and ascending order respectively ; If both numbers are even , smaller number should be placed at lower index ; If both numbers are odd larger number should be placed at lower index ; If a is odd and b is even , a should be placed before b ; If b is odd and a is even , b should be placed before a ; Driver code ; Sort the array ; Print the sorted array
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printArr ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; } bool compare ( int a , int b ) { if ( a % 2 == 0 && b % 2 == 0 ) return a < b ; if ( a % 2 != 0 && b % 2 != 0 ) return b < a ; if ( a % 2 != 0 ) return true ; return false ; } int main ( ) { int arr [ ] = { 1 , 3 , 2 , 7 , 5 , 4 } ; int n = sizeof ( arr ) / sizeof ( int ) ; sort ( arr , arr + n , compare ) ; printArr ( arr , n ) ; return 0 ; }