Sort by Parity
EasyPractice library · +10 XPsortingcustom order
Given a list of N integers, rearrange the list such that all even numbers appear before all odd numbers. Within the group of even numbers and within the group of odd numbers, the relative order of the elements does not matter. Print the rearranged list.
Input
The first line contains an integer N, the number of integers. The second line contains N space-separated integers.
Output
Print N space-separated integers, representing the rearranged list with even numbers preceding odd numbers.
Constraints
1 <= N <= 1000 -1000 <= a_i <= 1000, where a_i is the i-th integer.
Time limit 1 s (native code; slower languages get more)Memory 256 MB14 hidden tests
Example 1
Input
5 1 2 3 4 5
Output
2 4 1 3 5
Even numbers (2, 4) come before odd numbers (1, 3, 5).
Example 2
Input
6 2 4 6 1 3 5
Output
2 4 6 1 3 5
All even numbers are already before odd numbers.
Hints
# Read the input from stdin and print the answer.
import sys
def main():
data = sys.stdin.read().split()
# your code here
main()
Example 1 input
5 1 2 3 4 5
Example 2 input
6 2 4 6 1 3 5