# Program to sort an array based on the parity values in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

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

Live Demo

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]