159k views
2 votes
Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A.

Example 1: Input: [3,1,2,4] Output: [2,4,3,1]

This is the code there is to start:

def sortArrayByParity(A):
A = [3,1,2,4]
print(sortArrayByParity(A))

How do I iterate over the numbers to test if they are even or odd?

User Prag Rao
by
6.3k points

1 Answer

2 votes

Answer:

def sortArrayByParity(A):

array_length=len(A)

s=0

for i in range(0,array_length): #loop to iterate over the array

if A[i]%2 ==0: #if the number is even swap it with number at position s..

t=A[s]

A[s]=A[i]

A[i]=t

s=s+1 #increasing the count...

return A

A=list(map(int,input("Enter array elements : \\").strip().split()))#taking input of the array.

print(sortArrayByParity(A))#printing the array.

Step-by-step explanation:

My approach to do this question is to iterate over the array and take a pointer which points to the first index that is 0.If we encounter an even number swap it with first position element and increase the pointer and at last return the array.

User AnDx
by
5.3k points