Sort Array By Parity in Python

PythonServer Side ProgrammingProgramming

Suppose, we have an array A with some numbers. We have to arrange 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 seap arr[i] and arr[j], and increase i by 1
    • increase j by 1
  • return arr

Example

Let us see the following implementation to get better understanding −

 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()
print(ob1.sortArrayByParity([1,5,6,8,7,2,3]))

Input

[1,5,6,8,7,2,3]

Output

[6,8,2,5,7,1,3]
raja
Published on 16-Jan-2020 16:00:33
Advertisements