Given an array arr[]
of integers, the task is to partition the array based on even and odd elements. The partition has to be stable, meaning the relative ordering of all even elements must remain the same before and after partitioning, and the same should hold true for all odd elements.
Note: For a binary array (containing only 0s and 1s), this partition process is equivalent to sorting the array.
Examples:
Input: arr[] = [1, 0, 1, 1, 0, 0]
Output: [0 ,0 ,0, 1, 1, 1]
Explanation: All even numbers came before the odd numbers.
Input: arr[] = [1, 2, 3, 4, 5]
Output: [2, 4, 1, 3, 5]
Explanation: All even numbers [2, 4] came before the odd numbers [1, 3, 5], and the relative ordering was also same.
Input: arr[] = [-5, -2, 0, 4, 7, 9]
Output: [-2, 0, 4, -5, 7, 9]
Explanation: All even numbers [-2, 0, 4] came before the odd numbers [-5, 7, 9], and the relative ordering was also same.
The idea is to to use Naive Partitioning Algorithm, We use a temporary array to store the rearranged elements. We first iterate over the original array and add all the even elements to the temporary array, maintaining their original order. Next, we add all the odd elements to the temporary array in the same manner.
This guarantees that even elements appear before odd elements while preserving the relative order of similar elements. Finally, we copy the elements from the temporary array back into the original array.
C++
// C++ program to partition the array into even
// and odd elements using naive partition approach
#include <iostream>
#include <vector>
using namespace std;
// Function for stable partitioning of even-odd(binary) array
void partition(vector<int> &arr) {
int n = arr.size();
// create a temporary array to store the elements
vector<int> temp(n);
int idx = 0;
// First fill even elements into the temporary array
for (int i = 0; i < n; i++) {
if (arr[i] % 2 == 0)
temp[idx++] = arr[i];
}
// Now fill odd elements into the temporary array
for (int i = 0; i < n; i++) {
if (arr[i] & 1)
temp[idx++] = arr[i];
}
// copy the elements from temp to arr
arr = temp;
}
int main() {
vector<int> arr = {-5, -2, 0, 4, 7, 9};
partition(arr);
for (int i = 0; i < arr.size(); i++)
cout << arr[i] << " ";
return 0;
}
C
// C program to partition the array into even
// and odd elements using naive partition approach
#include <stdio.h>
#include <stdlib.h>
// Function for stable partitioning of even-odd(binary) array
void partition(int arr[], int n) {
// create a temporary array to store the elements
int *temp = (int *)malloc(n * sizeof(int));
int idx = 0;
// First fill even elements into the temporary array
for (int i = 0; i < n; i++) {
if (arr[i] % 2 == 0)
temp[idx++] = arr[i];
}
// Now fill odd elements into the temporary array
for (int i = 0; i < n; i++) {
if (arr[i] & 1)
temp[idx++] = arr[i];
}
// copy the elements from temp to arr
for (int i = 0; i < n; i++) {
arr[i] = temp[i];
}
free(temp);
}
int main() {
int arr[] = {-5, -2, 0, 4, 7, 9};
int n = sizeof(arr) / sizeof(arr[0]);
partition(arr, n);
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
Java
// Java program to partition the array into even
// and odd elements using naive partition approach
import java.util.Arrays;
class GfG {
// Function for stable partitioning of even-odd(binary) array
static void partition(int[] arr) {
int n = arr.length;
// create a temporary array to store the elements
int[] temp = new int[n];
int idx = 0;
// First fill even elements into the temporary array
for (int i = 0; i < n; i++) {
if (arr[i] % 2 == 0)
temp[idx++] = arr[i];
}
// Now fill odd elements into the temporary array
for (int i = 0; i < n; i++) {
if (arr[i] % 2 != 0)
temp[idx++] = arr[i];
}
// copy the elements from temp to arr
System.arraycopy(temp, 0, arr, 0, n);
}
public static void main(String[] args) {
int[] arr = {-5, -2, 0, 4, 7, 9};
partition(arr);
for (int i = 0; i < arr.length; i++)
System.out.print(arr[i] + " ");
}
}
Python
# Python program to partition the array into even
# and odd elements using naive partition approach
# Function for stable partitioning of even-odd(binary) array
def partition(arr):
# create a temporary list to store the elements
temp = []
# First fill even elements into the temporary list
for num in arr:
if num % 2 == 0:
temp.append(num)
# Now fill odd elements into the temporary list
for num in arr:
if num % 2 != 0:
temp.append(num)
# copy the elements from temp to arr
for i in range(len(arr)):
arr[i] = temp[i]
if __name__ == "__main__":
arr = [-5, -2, 0, 4, 7, 9]
partition(arr)
print(' '.join(map(str, arr)))
C#
// C# program to partition the array into even
// and odd elements using naive partition approach
using System;
class GfG {
// Function for stable partitioning of even-odd(binary) array
static void Partition(int[] arr) {
int n = arr.Length;
// create a temporary array to store the elements
int[] temp = new int[n];
int idx = 0;
// First fill even elements into the temporary array
for (int i = 0; i < n; i++) {
if (arr[i] % 2 == 0)
temp[idx++] = arr[i];
}
// Now fill odd elements into the temporary array
for (int i = 0; i < n; i++) {
if (arr[i] % 2 != 0)
temp[idx++] = arr[i];
}
// copy the elements from temp to arr
Array.Copy(temp, arr, n);
}
static void Main() {
int[] arr = {-5, -2, 0, 4, 7, 9};
Partition(arr);
Console.WriteLine(string.Join(" ", arr));
}
}
JavaScript
// JavaScript program to partition the array into even
// and odd elements using naive partition approach
// Function for stable partitioning of even-odd(binary) array
function partition(arr) {
// create a temporary array to store the elements
let temp = [];
// First fill even elements into the temporary array
for (let i = 0; i < arr.length; i++) {
if (arr[i] % 2 === 0)
temp.push(arr[i]);
}
// Now fill odd elements into the temporary array
for (let i = 0; i < arr.length; i++) {
if (arr[i] % 2 !== 0)
temp.push(arr[i]);
}
// copy the elements from temp to arr
for (let i = 0; i < arr.length; i++) {
arr[i] = temp[i];
}
}
// Driver Code
let arr = [-5, -2, 0, 4, 7, 9];
partition(arr);
console.log(arr.join(' '));
Time Complexity: O(n), for traversing the array.
Auxiliary Space: O(n), for temporary array.
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read