
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to sort an array based on the parity values in Python
Suppose, we have an array A with few integers. We have to sort the numbers as even then odd. So put the even numbers at first, then the odd numbers. So if the array is like A = [1, 5, 6, 8, 7, 2, 3], then the result will be like [6, 8, 2, 1, 5, 7, 3]
To solve this, we will follow these steps −
set i := 0 and j := 0
while j < size of arr
if arr[j] is even, then
swap arr[i] and arr[j],
increase i by 1
increase j by 1
return arr
Let us see the following implementation to get better understanding −
Example
class Solution(object): def sortArrayByParity(self, a): i = 0 j =0 while j < len(a): if a[j]%2==0: a[i],a[j] = a[j],a[i] i+=1 j+=1 return a ob1 = Solution() nums = [1,5,6,8,7,2,3] print(ob1.sortArrayByParity(nums))
Input
[1,5,6,8,7,2,3]
Output
[6,8,2,5,7,1,3]
- Related Articles
- Sort Array By Parity in Python
- Program to sort out phrases based on their appearances in Python
- Sort array based on another array in JavaScript
- Python program to sort table based on given attribute index
- How to sort an array of objects based on the length of a nested array in JavaScript
- C program to sort triangles based on area
- Program to sort numbers based on 1 count in their binary representation in Python
- Program to sort given set of Cartesian points based on polar angles in Python
- How to sort volley json array based on id in android?
- Python program to sort the elements of an array in ascending order
- Python program to sort the elements of an array in descending order
- Swift Program to fetch elements from an array based on an index
- Golang program to fetch elements from an array based on an index
- Sort object array based on another array of keys - JavaScript
- Program to perform bubble sort based on choice in 8085 Microprocessor

Advertisements