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

PythonServer Side ProgrammingProgramming

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]
raja
Published on 21-Oct-2020 11:07:05
Advertisements