# Sort all even numbers in ascending order and then sort all odd numbers in descending order

• Difficulty Level : Easy
• Last Updated : 08 Jul, 2022

Given an array of integers (both odd and even), sort them in such a way that the first part of the array contains odd numbers sorted in descending order, rest portion contains even numbers sorted in ascending order.
Examples:

Input: arr[] = {1, 2, 3, 5, 4, 7, 10}
Output: arr[] = {7, 5, 3, 1, 2, 4, 10}

Input: arr[] = {0, 4, 5, 3, 7, 2, 1}
Output: arr[] = {7, 5, 3, 1, 0, 2, 4}

Recommended Practice

Method 1 (Using Partition)

1. Partition the input array such that all odd elements are moved to the left and all even elements on right. This step takes O(n).
2. Once the array is partitioned, sort left and right parts individually. This step takes O(n Log n).

Below is the implementation of the above idea.

## C++

 // C++ program sort array in even and odd manner.// The odd numbers are to be sorted in descending// order and the even numbers in ascending order#include using namespace std; // To do two way sort. First sort even numbers in// ascending order, then odd numbers in descending// order.void twoWaySort(int arr[], int n){         // Current indexes from left and right    int l = 0, r = n - 1;     // Count of odd numbers    int k = 0;     while (l < r)    {             // Find first even number        // from left side.        while (arr[l] % 2 != 0)        {            l++;            k++;        }         // Find first odd number        // from right side.        while (arr[r] % 2 == 0 && l < r)            r--;         // Swap even number present on left and odd        // number right.        if (l < r)            swap(arr[l], arr[r]);    }     // Sort odd number in descending order    sort(arr, arr + k, greater());     // Sort even number in ascending order    sort(arr + k, arr + n);} // Driver codeint main(){    int arr[] = { 1, 3, 2, 7, 5, 4 };    int n = sizeof(arr) / sizeof(int);    twoWaySort(arr, n);    for (int i = 0; i < n; i++)        cout << arr[i] << " ";    return 0;}

## Java

 // Java program sort array in even and odd manner.// The odd numbers are to be sorted in descending// order and the even numbers in ascending order import java.util.Arrays;import java.util.Collections; public class GFG {    // To do two way sort. First sort even numbers in    // ascending order, then odd numbers in descending    // order.    static void twoWaySort(Integer arr[], int n)    {        // Current indexes from left and right        int l = 0, r = n - 1;         // Count of odd numbers        int k = 0;         while (l < r)        {                     // Find first even number from left side.            while (arr[l] % 2 != 0)            {                l++;                k++;            }             // Find first odd number from right side.            while (arr[r] % 2 == 0 && l < r)                r--;             // Swap even number present on left and odd            // number right.            if (l < r)            {                             // swap arr[l] arr[r]                int temp = arr[l];                arr[l] = arr[r];                arr[r] = temp;            }        }         // Sort odd number in descending order        Arrays.sort(arr, 0, k, Collections.                                  reverseOrder());         // Sort even number in ascending order        Arrays.sort(arr, k, n);    }     // Driver Method    public static void main(String[] args)    {        Integer arr[] = { 1, 3, 2, 7, 5, 4 };         twoWaySort(arr, arr.length);         System.out.println(Arrays.toString(arr));    }}

## Python

 # Python program to sort array# in even and odd manner# The odd numbers are to be# sorted in descending order# and the even numbers in# ascending order # To do two way sort. First# sort even numbers in ascending# order, then odd numbers in# descending order.def two_way_sort(arr, arr_len):         # Current indexes l->left    # and r->right    l, r = 0, arr_len - 1         # Count of number of    # odd numbers, used in    # slicing the array later.    k = 0         # Run till left(l) < right(r)    while(l < r):                 # While left(l) is odd, if yes        # increment the left(l) plus        # odd count(k) if not break the        # while for even number found        # here to be swapped        while(arr[l] % 2 != 0):            l += 1            k += 1                     # While right(r) is even,        # if yes decrement right(r)        # if not break the while for        # odd number found here to        # be swapped            while(arr[r] % 2 == 0 and l < r):            r -= 1                     # Swap the left(l) and right(r),        # which is even and odd numbers        # encountered in above loops        if(l < r):            arr[l], arr[r] = arr[r], arr[l]                 # Slice the number on the    # basis of odd count(k)    odd = arr[:k]    even = arr[k:]         # Sort the odd and    # even array accordingly    odd.sort(reverse = True)    even.sort()         # Extend the odd array with    # even values and return it.    odd.extend(even)         return odd     # Driver codearr_len = 6arr = [1, 3, 2, 7, 5, 4]result = two_way_sort(arr, arr_len)for i in result:    print(str(i) + " "), # This code is contributed# by JaySiyaRam

## C#

 // C# program sort array in even and odd manner.// The odd numbers are to be sorted in descending// order and the even numbers in ascending orderusing System;using System.Linq; class GFG {    // To do two way sort. First sort even numbers in    // ascending order, then odd numbers in descending    // order.    static void twoWaySort(int[] arr, int n)    {        // Current indexes from left and right        int l = 0, r = n - 1;         // Count of odd numbers        int k = 0;         while (l < r)        {                     // Find first even number            // from left side.            while (arr[l] % 2 != 0)            {                l++;                k++;            }             // Find first odd number from right side.            while (arr[r] % 2 == 0 && l < r)                r--;             // Swap even number present            // on left and odd            // number right.            if (l < r) {                // swap arr[l] arr[r]                int temp = arr[l];                arr[l] = arr[r];                arr[r] = temp;            }        }         // Sort odd number in descending order        Array.Sort(arr, 0, k);        Array.Reverse(arr, 0, k);         // Sort even number in ascending order        Array.Sort(arr, k, n - k);    }     // Driver Method    public static void Main(String[] args)    {        int[] arr = { 1, 3, 2, 7, 5, 4 };         twoWaySort(arr, arr.Length);         Console.WriteLine(String.Join(" ", arr));    }} // This code has been contributed by 29AjayKumar

## Javascript



Output

7 5 3 1 2 4

Time complexity: O(n log n)
Auxiliary Space: O(1)

Method 2 (Using negative multiplication) :

1. Make all odd numbers negative.
2. Sort all numbers.
3. Revert the changes made in step 1 to get original elements back.

Implementation:

## C++

 // C++ program sort array in even and odd manner.// The odd numbers are to be sorted in descending// order and the even numbers in ascending order#include using namespace std; // To do two way sort. First sort even numbers in// ascending order, then odd numbers in descending// order.void twoWaySort(int arr[], int n){    // Make all odd numbers negative    for (int i = 0; i < n; i++)        if (arr[i] & 1) // Check for odd            arr[i] *= -1;     // Sort all numbers    sort(arr, arr + n);     // Retaining original array    for (int i = 0; i < n; i++)        if (arr[i] & 1)            arr[i] *= -1;} // Driver codeint main(){    int arr[] = { 1, 3, 2, 7, 5, 4 };    int n = sizeof(arr) / sizeof(int);    twoWaySort(arr, n);    for (int i = 0; i < n; i++)        cout << arr[i] << " ";    return 0;}

## Java

 // Java program sort array in even and odd manner.// The odd numbers are to be sorted in descending// order and the even numbers in ascending order import java.util.Arrays; public class GFG{    // To do two way sort. First sort even numbers in    // ascending order, then odd numbers in descending    // order.    static void twoWaySort(int arr[], int n)    {        // Make all odd numbers negative        for (int i = 0; i < n; i++)            if ((arr[i] & 1) != 0) // Check for odd                arr[i] *= -1;         // Sort all numbers        Arrays.sort(arr);         // Retaining original array        for (int i = 0; i < n; i++)            if ((arr[i] & 1) != 0)                arr[i] *= -1;    }     // Driver Method    public static void main(String[] args)    {        int arr[] = { 1, 3, 2, 7, 5, 4 };         twoWaySort(arr, arr.length);         System.out.println(Arrays.toString(arr));    }}

## Python3

 # Python 3 program to sort array in# even and odd manner. The odd# numkbers are to be sorted in# descending order and the even# numbers in ascending order # To do two way sort. First sort# even numbers in ascending order,# then odd numbers in descending order.def twoWaySort(arr, n):     # Make all odd numbers negative    for i in range(0, n):                 # Check for odd        if (arr[i] & 1):            arr[i] *= -1     # Sort all numbers    arr.sort()     # Retaining original array    for i in range(0, n):        if (arr[i] & 1):            arr[i] *= -1 # Driver codearr = [1, 3, 2, 7, 5, 4]n = len(arr)twoWaySort(arr, n);for i in range(0, n):    print(arr[i], end = " ")     # This code is contributed by Smitha Dinesh Semwal

## C#

 // Java program sort array in even and// odd manner. The odd numbers are to// be sorted in descending order and// the even numbers in ascending orderusing System; public class GFG{     // To do two way sort. First sort    // even numbers in ascending order,    // then odd numbers in descending    // order.    static void twoWaySort(int[] arr, int n)    {         // Make all odd numbers negative        for (int i = 0; i < n; i++)             // Check for odd            if ((arr[i] & 1) != 0)                arr[i] *= -1;         // Sort all numbers        Array.Sort(arr);         // Retaining original array        for (int i = 0; i < n; i++)            if ((arr[i] & 1) != 0)                arr[i] *= -1;    }     // Driver Method    public static void Main()    {        int[] arr = { 1, 3, 2, 7, 5, 4 };         twoWaySort(arr, arr.Length);         for (int i = 0; i < arr.Length; i++)            Console.Write(arr[i] + " ");    }} // This code is contributed by Smitha



## Javascript



Output

7 5 3 1 2 4

Time complexity: O(n log n)
Auxiliary Space: O(1)

This method may not work when input array contains negative numbers. However, there is a way to handle this. We count the positive odd integers in the input array then sort again. Readers may refer this for implementation.

Method 3 (Using comparator):
This problem can be easily solved by using the inbuilt sort function with a custom compare method. On comparing any two elements there will be three cases:

1. When both the elements are even: In this case, the smaller element must appear in the left of the larger element in the sorted array.
2. When both the elements are odd: The larger element must appear on left of the smaller element.
3. One is odd and the other is even: The element which is odd must appear on the left of the even element.

Below is the implementation of the above approach:

## CPP

 // C++ implementation of the approach#include using namespace std; // Utility function to print// the contents of the arrayvoid printArr(int arr[], int n){    for (int i = 0; i < n; i++)        cout << arr[i] << " ";} // 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 respectivelybool compare(int a, int b){         // If both numbers are even,    // smaller number should    // be placed at lower index    if (a % 2 == 0 && b % 2 == 0)        return a < b;     // If both numbers are odd larger number    // should be placed at lower index    if (a % 2 != 0 && b % 2 != 0)        return b < a;     // If a is odd and b is even,    // a should be placed before b    if (a % 2 != 0)        return true;     // If b is odd and a is even,    // b should be placed before a    return false;} // Driver codeint main(){    int arr[] = { 1, 3, 2, 7, 5, 4 };    int n = sizeof(arr) / sizeof(int);     // Sort the array    sort(arr, arr + n, compare);     // Print the sorted array    printArr(arr, n);     return 0;} // This code is contributed by Nikhil Yadav

## Java

 // Java implementation of the approachimport java.util.ArrayList;import java.util.Collections;import java.util.Comparator; class GFG{     // Utility function to print    // the contents of the array    static void printArr(ArrayList arr, int n) {        for (int i = 0; i < n; i++)            System.out.print(arr.get(i) + " ");    }     // Driver code    public static void main(String args[]) {        ArrayList arr = new ArrayList();        arr.add(1);        arr.add(3);        arr.add(2);        arr.add(7);        arr.add(5);        arr.add(4);        int n = arr.size();          // Sort the array        Collections.sort(arr, new Comparator() {            @Override            public int compare(Integer a, Integer b) {                 // If both numbers are even,                // smaller number should                // be placed at lower index                if (a % 2 == 0 && b % 2 == 0)                    return (a - b);                 // If both numbers are odd larger number                // should be placed at lower index                if (a % 2 != 0 && b % 2 != 0)                    return (b - a);                 // If a is odd and b is even,                // a should be placed before b                if (a % 2 != 0)                    return -1;                 // If b is odd and a is even,                // b should be placed before a                return 0;            }        });                 // Print the sorted array        printArr(arr, n);    }} // This code is contributed by Saurabh Jaiswal

## Python3

 # Python3 implementation of the approach # Utility function to print# the contents of the arrayfrom functools import cmp_to_key def printArr(arr, n):                 for i in range(n):        print(arr[i], end = " ")         # 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 respectivelydef compare(a, b):     # If both numbers are even,    # smaller number should    # be placed at lower index    if (a % 2 == 0 and b % 2 == 0 and a < b):        return -1     # If both numbers are odd larger number    # should be placed at lower index    if (a % 2 != 0 and b % 2 != 0 and b > a):        return 1     # If a is odd and b is even,    # a should be placed before b    if (a % 2 != 0):        return -1     # If b is odd and a is even,    # b should be placed before a    return 1 # Driver codearr = [1, 3, 2, 7, 5, 4]n = len(arr) # Sort the arrayarr.sort(key = cmp_to_key(compare)) # Print the sorted arrayprintArr(arr, n)         # This code is contributed by shinjanpatra

## C#

 // C# implementation of the approachusing System;using System.Collections.Generic; public class GFG{   // Utility function to print  // the contents of the array  static void printArr(List arr, int n) {    for (int i = 0; i < n; i++)      Console.Write(arr[i] + " ");  }  private static int Compare(int a, int b)  {     // If both numbers are even,    // smaller number should    // be placed at lower index    if (a % 2 == 0 && b % 2 == 0 && aa)      return 1;     // If a is odd and b is even,    // a should be placed before b    if (a % 2 != 0)      return -1;     // If b is odd and a is even,    // b should be placed before a    return 1;  }   // Driver code  public static void Main(String []args) {    List arr = new List();    arr.Add(1);    arr.Add(3);    arr.Add(2);    arr.Add(7);    arr.Add(5);    arr.Add(4);    int n = arr.Count;     // Sort the array    arr.Sort(Compare);     // Print the sorted array    printArr(arr, n);  }}  // This code is contributed by 29AjayKumar

## Javascript



Output

7 5 3 1 2 4

Time complexity : O(n*logn) [sort function has average time complexity n*logn]
Auxiliary Space : O(1)

Thanks to Amandeep Singh for suggesting this solution.

This article is contributed by DANISH_RAZA. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

My Personal Notes arrow_drop_up