- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Program to sort all even and odd numbers in increasing and decreasing order respectively in Python

Suppose we have a list of numbers called nums, we have to sort the array by maintaining following criteria

- Even numbers are sorted in ascending order
- Odd numbers are sorted in descending order
- The relative positions of the even and odd numbers should not be changed.

So, if the input is like [9, 14, 12, 91, -4, 5], then the output will be [91, -4, 12, 9, 14, 5]

To solve this, we will follow these steps −

- evens := list of even terms in nums array
- odds := list of odd terms in nums array
- sort the list evens
- even_i := 0, odd_i := 0
- for index in range 0 to size of nums, do
- if nums[index] mod 2 is same as 0, then
- nums[index] := evens[even_i]
- even_i := even_i + 1

- otherwise,
- nums[index] := odds[odd_i]
- odd_i := odd_i + 1

- if nums[index] mod 2 is same as 0, then
- return nums

Let us see the following implementation to get better understanding −

## Example

class Solution: def solve(self, nums): evens = [num for num in nums if num % 2 == 0] odds = [num for num in nums if num % 2 != 0] evens.sort() odds.sort(reverse=True) even_i = 0 odd_i = 0 for index in range(len(nums)): if nums[index] % 2 == 0: nums[index] = evens[even_i] even_i += 1 else: nums[index] = odds[odd_i] odd_i += 1 return nums ob = Solution() print(ob.solve([9, 14, 12, 91, -4, 5]))

## Input

[9, 14, 12, 91, -4, 5]

## Output

[91, -4, 12, 9, 14, 5]

- Related Articles
- Python program to Count Even and Odd numbers in a List
- Python Program for Odd-Even Sort / Brick Sort
- Python program to sort tuples in increasing order by any key.
- Even numbers at even index and odd numbers at odd index in C++
- Print array elements in alternatively increasing and decreasing order in C++
- Sort Tuples in Increasing Order by any key in Python program
- How to sort a vector in increasing order that contains numbers and characters in R?
- Implementing insertion sort to sort array of numbers in increasing order using JavaScript
- Swift Program to Get Odd and Even Numbers From the Array
- C/C++ Program for Odd-Even Sort (Brick Sort)?
- What are even and odd numbers?
- Python program to print all odd numbers in a range
- Decreasing order sort of alphabets in JavaScript
- Python program to print all even numbers in a range
- C program to store even, odd and prime numbers into separate files

Advertisements