- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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]
Advertisements