[Array] Sort Array By Parity - Easy

Sorting an array by parity means we want to move all even numbers to the front and all odd numbers to the back. This is a simple method. We can use it in many programming languages like Java, Python, and C++. With good algorithms, we can do this quickly. We can sort in linear time. This helps us keep things easy and fast.

In this article, we will look at how to sort an array by parity in different programming languages. We will show ways to sort arrays using basic loops and two-pointer methods. We will also talk about list comprehensions in Python. Plus, we will check in-place sorting in Java and C++. We will also see how well these methods work. We will answer some common questions about sorting arrays by parity.

  • Sort Array By Parity in Java Implementation
  • Sort Array By Parity in Python Implementation
  • Sort Array By Parity in C++ Implementation
  • Two Pointer Approach to Sort Array By Parity
  • Using List Comprehensions to Sort Array By Parity in Python
  • In Place Sorting of Array By Parity in Java
  • Sorting Array By Parity with Stream API in Java
  • Sorting Array By Parity Using Standard Template Library in C++
  • Performance Analysis of Array Sort By Parity Solutions
  • Frequently Asked Questions

If you want to read more about arrays, you can check out articles like Array - Two Sum and Array - Contains Duplicate.

Sort Array By Parity in Python Implementation

To sort an array by parity in Python, we can split the even and odd numbers. Then we can join them together. Here’s a simple way to do this using list comprehensions:

def sort_array_by_parity(arr):
    return [x for x in arr if x % 2 == 0] + [x for x in arr if x % 2 != 0]

# Example usage
input_array = [3, 1, 2, 4]
sorted_array = sort_array_by_parity(input_array)
print(sorted_array)  # Output: [2, 4, 3, 1]

This function goes through the input array two times. First for even numbers and second for odd numbers. This way, the result keeps the order of even numbers first and odd numbers after.

If we want to sort the array without using extra space, we can use the two-pointer method:

def sort_array_by_parity_in_place(arr):
    left, right = 0, len(arr) - 1
    while left < right:
        if arr[left] % 2 > arr[right] % 2:
            arr[left], arr[right] = arr[right], arr[left]
        if arr[left] % 2 == 0:
            left += 1
        if arr[right] % 2 == 1:
            right -= 1
    return arr

# Example usage
input_array = [3, 1, 2, 4]
sorted_array = sort_array_by_parity_in_place(input_array)
print(sorted_array)  # Output: [4, 2, 3, 1]

This method changes the array directly. It moves even numbers to the front and odd numbers to the back. It does not need extra space.

For more tips on array manipulation techniques, we can check out Array contains duplicate - Easy.

Sort Array By Parity in C++ Implementation

In C++, we sort an array by parity to put all even numbers before odd numbers. We can do this well with a two-pointer method or using the Standard Template Library (STL).

C++ Code Implementation

Here is a simple code using the two-pointer method:

#include <iostream>
#include <vector>

std::vector<int> sortArrayByParity(std::vector<int>& A) {
    int left = 0, right = A.size() - 1;
    
    while (left < right) {
        if (A[left] % 2 > A[right] % 2) {
            std::swap(A[left], A[right]);
        }
        if (A[left] % 2 == 0) left++;
        if (A[right] % 2 == 1) right--;
    }
    
    return A;
}

int main() {
    std::vector<int> arr = {3, 1, 2, 4};
    std::vector<int> sortedArray = sortArrayByParity(arr);
    
    for (int num : sortedArray) {
        std::cout << num << " ";
    }
    return 0;
}

Explanation of the Code

  • Two Pointers: The left pointer starts at the start of the array. The right pointer starts at the end of the array.
  • Swap Condition: If the number at the left pointer is odd and the number at the right pointer is even, we swap them.
  • Pointer Movement: After we check, the left pointer moves right if the number is even. The right pointer moves left if the number is odd.
  • Output: The new array will have all even numbers in front and then odd numbers.

Performance

This solution runs in O(n) time. Here n is the number of elements in the array. It uses O(1) extra space because it sorts the array in place.

For more about working with arrays, you can read these topics: - Array Two Sum - Easy - Array Remove Duplicates from Sorted Array - Easy

Two Pointer Approach to Sort Array By Parity

We can use the two-pointer approach to sort an array by parity. This way is efficient. It uses two pointers to change the elements in one go. One pointer starts from the beginning of the array. The other pointer starts from the end. The pointers move towards each other. They swap elements to make sure even numbers are on the left and odd numbers are on the right.

Java Implementation

public int[] sortArrayByParity(int[] A) {
    int left = 0, right = A.length - 1;
    while (left < right) {
        if (A[left] % 2 > A[right] % 2) {
            int temp = A[left];
            A[left] = A[right];
            A[right] = temp;
        }
        if (A[left] % 2 == 0) left++;
        if (A[right] % 2 == 1) right--;
    }
    return A;
}

Python Implementation

def sort_array_by_parity(A):
    left, right = 0, len(A) - 1
    while left < right:
        if A[left] % 2 > A[right] % 2:
            A[left], A[right] = A[right], A[left]
        if A[left] % 2 == 0:
            left += 1
        if A[right] % 2 == 1:
            right -= 1
    return A

C++ Implementation

vector<int> sortArrayByParity(vector<int>& A) {
    int left = 0, right = A.size() - 1;
    while (left < right) {
        if (A[left] % 2 > A[right] % 2) {
            swap(A[left], A[right]);
        }
        if (A[left] % 2 == 0) left++;
        if (A[right] % 2 == 1) right--;
    }
    return A;
}

This two-pointer method works in O(n) time and O(1) space. It is a good solution for sorting an array by parity. It separates even and odd numbers without needing more space for another array.

For more algorithms about arrays, we can check Array Two Sum or Array Contains Duplicate.

Using List Comprehensions to Sort Array By Parity in Python

In Python, we can use list comprehensions to sort an array by parity in a smart way. The main idea is to make a new list where all even numbers come before the odd numbers. This way is simple and takes advantage of Python’s list comprehension.

Here is how we can do it:

def sort_array_by_parity(arr):
    return [x for x in arr if x % 2 == 0] + [x for x in arr if x % 2 != 0]

# Example usage
input_array = [3, 1, 2, 4]
sorted_array = sort_array_by_parity(input_array)
print(sorted_array)  # Output: [2, 4, 3, 1]

Explanation:

  • The first list comprehension [x for x in arr if x % 2 == 0] gets all even numbers.
  • The second list comprehension [x for x in arr if x % 2 != 0] gets all odd numbers.
  • Then, we join the two lists. This way, all even numbers are before odd numbers.

This method is quick and easy to read. If you want to learn more about how to work with arrays, we can check out the article on Array Contains Duplicate.

In Place Sorting of Array By Parity in Java

In Java, we can sort an array by parity in-place using a two-pointer method. This way, we rearrange the elements of the array without needing extra space for another array.

Here is how we can do it:

public class SortArrayByParity {
    public static int[] sortArrayByParity(int[] A) {
        int left = 0, right = A.length - 1;
        while (left < right) {
            while (left < right && A[left] % 2 == 0) {
                left++;
            }
            while (left < right && A[right] % 2 == 1) {
                right--;
            }
            if (left < right) {
                int temp = A[left];
                A[left] = A[right];
                A[right] = temp;
            }
        }
        return A;
    }

    public static void main(String[] args) {
        int[] array = {3, 1, 2, 4};
        int[] sortedArray = sortArrayByParity(array);
        for (int num : sortedArray) {
            System.out.print(num + " ");
        }
    }
}

Explanation:

  • Two Pointers: One pointer (left) starts at the beginning. The other pointer (right) starts at the end of the array.
  • Even Check: The left pointer moves forward until it finds an odd number.
  • Odd Check: The right pointer moves backward until it finds an even number.
  • Swap: If left is less than right, we swap the odd and even numbers.

This way sorts the array in-place with a time complexity of O(n) and space complexity of O(1). This is the best way to sort an array by parity in Java.

For more tips on working with arrays, we can check the Array Two Sum tutorial.

Sorting Array By Parity with Stream API in Java

In Java, we can use the Stream API to sort an array by parity easily. This means we will separate the even and odd numbers first. Then we will put them back together. Let’s see how we can do this with the Stream API.

Java Implementation Using Stream API

We can change the array into a stream, filter out the even and odd numbers, and then join the results. Here is a simple example:

import java.util.Arrays;

public class SortArrayByParity {
    public static void main(String[] args) {
        int[] nums = {3, 1, 2, 4};
        int[] sortedArray = sortArrayByParity(nums);
        System.out.println(Arrays.toString(sortedArray));
    }

    public static int[] sortArrayByParity(int[] A) {
        return Arrays.stream(A)
                     .boxed()
                     .sorted((a, b) -> Integer.compare(a % 2, b % 2))
                     .mapToInt(i -> i)
                     .toArray();
    }
}

Explanation of the Code

  • Arrays.stream(A): This changes the array into a stream.
  • .boxed(): This changes the int stream into a Stream<Integer>.
  • .sorted((a, b) -> Integer.compare(a % 2, b % 2)): This sorts the numbers based on if they are even or odd. Even numbers come first.
  • .mapToInt(i -> i): This changes the Stream<Integer> back into an IntStream.
  • .toArray(): This collects the numbers into a new array.

This way is short and clear. We use the Stream API to sort the array by parity in a good way.

If we want to learn more about arrays and how to make them better, we can check out Array Two Sum or Array Contains Duplicate.

Sorting Array By Parity Using Standard Template Library in C++

We can sort an array by parity in C++ using the Standard Template Library (STL). We use the std::stable_partition function for this. This function changes the order of elements. It puts all even numbers before all odd numbers. The even and odd numbers keep their original order.

Here is a simple example:

#include <iostream>
#include <vector>
#include <algorithm>

void sortArrayByParity(std::vector<int>& nums) {
    std::stable_partition(nums.begin(), nums.end(), [](int x) { return x % 2 == 0; });
}

int main() {
    std::vector<int> nums = {3, 1, 2, 4};
    sortArrayByParity(nums);
    
    for (int num : nums) {
        std::cout << num << " ";
    }
    return 0;
}

Explanation:

  • std::stable_partition: This is a function from STL. We use it to partition the array based on a rule we set with a lambda function. Here, we check if a number is even.
  • Lambda Function: [](int x) { return x % 2 == 0; } gives true for even numbers.

Properties:

  • Time Complexity: O(n). Here, n is how many elements are in the array.
  • Space Complexity: O(n). This is for the extra storage that the partition function needs.

This method sorts the array by parity well. It keeps the order of the elements and uses the C++ Standard Template Library.

For more ways to work with arrays in C++, visit Sorting Array By Parity with Stream API in Java for more ideas.

Performance Analysis of Array Sort By Parity Solutions

We can look at how well sorting an array by parity works. We can think about time complexity, space complexity, and the algorithm we use. Here are the main points to keep in mind:

  • Time Complexity:
    • Most ways to sort an array by parity work in O(n) time. Here, n means the number of items in the array. We can do this because we can separate even and odd numbers in one go.
    • If we use methods that need sorting, the complexity can go up to O(n log n). But we do not need this for parity sorting since we only rearrange based on even and odd.
  • Space Complexity:
    • We should prefer in-place algorithms that use constant space, which is O(1). For example, the two-pointer method does not need extra arrays.
    • If we make new lists or arrays to hold even and odd numbers, this has O(n) space complexity.
  • Algorithm Comparison:
    • Two Pointer Approach: This is fast with O(n) time and O(1) space. It uses two pointers to go through and swap elements directly.
    • List Comprehensions in Python: This method looks nice but may use extra space and has a time complexity of O(n).
    • Stream API in Java: It gives a short way to sort, but it can be slower than the two-pointer method. It usually takes O(n) for processing but may have extra costs.
  • Real-World Performance:
    • Which algorithm we choose can depend on how big the input data is and how much memory we have. For large datasets, we should use in-place methods.
    • Tests in different programming languages like Java, Python, and C++ show that the two-pointer method is usually faster and uses memory better than list-based methods.

In short, the two-pointer approach is the best way to sort an array by parity. It gives us good time complexity and uses little space. The way we implement it may change based on the programming tools we use, but we should focus on performance for big datasets.

Frequently Asked Questions

1. What is the best algorithm to sort an array by parity?

We can sort an array by parity easily with the two-pointer technique. This method uses two pointers. One pointer is for even numbers and the other is for odd numbers. This way, we can rearrange the elements quickly. You can find more details in our guide on the two-pointer approach to sort array by parity.

2. Can I sort an array by parity in Python using list comprehensions?

Yes, we can use Python’s list comprehensions to sort an array by parity. We can filter even and odd numbers separately. Then we can join them to get the result in one line of code. Check our section on using list comprehensions to sort array by parity in Python for a simple example.

3. How do I sort an array by parity in Java?

In Java, we can sort an array by parity using different methods. We can use the two-pointer technique or the Stream API. The two-pointer method swaps elements directly. The Stream API gives a different way to do it. Learn more about these methods in our sections on in-place sorting of array by parity in Java and sorting array by parity with Stream API in Java.

4. Is it possible to sort an array by parity in C++?

Yes, it is possible! C++ has the Standard Template Library (STL). We can use STL to sort an array by parity well. By using std::vector and going through the elements, we can separate even and odd numbers fast. For more details, look at our section on sorting array by parity using Standard Template Library in C++.

5. What are the performance considerations when sorting an array by parity?

When we sort an array by parity, the time complexity can be as low as O(n) if we use in-place methods like the two-pointer technique. But the space complexity can change based on the method we choose. For a deep look at performance, visit our performance analysis of array sort by parity solutions section to see the trade-offs.

Feel free to explore more about arrays and their features in our related articles, like Array Two Sum and Array Contains Duplicate.