The Wayback Machine - https://web.archive.org/web/20240818163943/https://www.geeksforgeeks.org/segregate-even-odd-numbers-set-3/
Open In App

Segregate even and odd numbers using Lomuto’s Partition Scheme

Last Updated : 10 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an array arr[] of integers, segregate even and odd numbers in the array such that all the even numbers should be present first, and then the odd numbers.

Examples:  

Input: arr[] = {7, 2, 9, 4, 6, 1, 3, 8, 5}
Output: 2 4 6 8 7 9 1 3 5

Input: arr[] = {1, 3, 2, 4, 7, 6, 9, 10}
Output:  2 4 6 10 7 1 9 3

We have discussed two different approaches in below posts: 

Approach: The optimization for the above approach is based on Lomuto’s Partition Scheme 

  • Start with an array of numbers.

For the sake of illustration, let’s consider the following array: [7, 2, 9, 4, 6, 1, 3, 8, 5].

  • Choose a pivot element from the array.

In this case, let’s choose the last element, which is 5, as the pivot.

  • Initialize two pointers, i and j.
    • The pointer i will keep track of the boundary between the even and odd numbers, and
    • the pointer j will iterate through the array.
  • Iterate through the array using the pointer j.
    • Compare each element with the pivot and perform the following steps:
      • If the element is even, swap it with the element at index i and increment i.
      • If the element is odd, do nothing and continue.

Let’s go through the steps:

  • Initially, i = 0 and j = 0.
  • The first element is 7 (odd),
    • so we do nothing and move j to the next element.
  • The second element is 2 (even),
    • so we swap it with the element at index i (which is also 2) and increment i to 1.
  • The third element is 9 (odd),
    • so we do nothing and move j to the next element.
  • The fourth element is 4 (even),
    • so we swap it with the element at index i (which is 9) and increment i to 2.
  • The fifth element is 6 (even),
    • so we swap it with the element at index i (which is 9) and increment i to 3.
  • The sixth element is 1 (odd),
    • so we do nothing and move j to the next element.
  • The seventh element is 3 (odd),
    • so we do nothing and move j to the next element.
  • The eighth element is 8 (even),
    • so we swap it with the element at index i (which is 1) and increment i to 4.
  • The ninth element is 5 (odd),
    • so we do nothing and move j to the next element.
  • After iterating through the array, we partitioned the even and odd numbers.

The array now looks like this: [2, 4, 6, 8, 5, 1, 3, 9, 7].

  • Finally, swap the pivot element with the element at index I.

In this case, we swap 5 with 7. This step ensures that the pivot element is in its final sorted position.

The array after the final swap will be: [2, 4, 6, 8, 7, 1, 3, 9, 5].

  • Now, the even numbers are on the left side of the pivot, and the odd numbers are on the right side. The pivot element is in its correct sorted position.

Below is the implementation of the above approach: 

C++
// CPP code to segregate even odd
// numbers in an array
#include <bits/stdc++.h>
using namespace std;

// Function to segregate even odd numbers
vector<int> arrayEvenAndOdd(vector<int>& arr)
{

    int i = -1, j = 0;
    int pivot = arr.back();
    for (j = 0; j < arr.size() - 1; j++) {
        if (arr[j] % 2 == 0) {
            i++;

            // Swapping even and odd numbers
            swap(arr[i], arr[j]);
        }
    }

    swap(arr[i + 1], arr.back());
    return arr;
}

// Driver code
int main()
{
    vector<int> arr = { 7, 2, 9, 4, 6, 1, 3, 8, 5 };
    vector<int> updatedArr = arrayEvenAndOdd(arr);

    // Function Call
    cout << "Updated Array: ";
    for (int num : updatedArr) {
        cout << num << " ";
    }
    cout << endl;

    return 0;
}
Java
// java code to segregate even odd
// numbers in an array
public class GFG {

    // Function to segregate even
    // odd numbers
    static void arrayEvenAndOdd(int arr[], int n)
    {

        int i = -1, j = 0;
        while (j != n) {
            if (arr[j] % 2 == 0) {
                i++;

                // Swapping even and
                // odd numbers
                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
            j++;
        }

        // Printing segregated array
        for (int k = 0; k < n; k++)
            System.out.print(arr[k] + " ");
    }

    // Driver code
    public static void main(String args[])
    {
        int arr[] = { 1, 3, 2, 4, 7, 6, 9, 10 };
        int n = arr.length;
        arrayEvenAndOdd(arr, n);
    }
}

// This code is contributed by Sam007
Python
# Python3 code to segregate even odd
# numbers in an array

# Function to segregate even odd numbers


def arrayEvenAndOdd(arr, n):
    i = -1
    j = 0
    while (j != n):
        if (arr[j] % 2 == 0):
            i = i+1

            # Swapping even and odd numbers
            arr[i], arr[j] = arr[j], arr[i]

        j = j+1

    # Printing segregated array
    for i in arr:
        print(str(i) + " ", end='')


# Driver Code
if __name__ == '__main__':
    arr = [1, 3, 2, 4, 7, 6, 9, 10]
    n = len(arr)
    arrayEvenAndOdd(arr, n)

# This code was contributed by
# Yatin Gupta
C#
// C# code to segregate even odd
// numbers in an array
using System;

class GFG {

    // Function to segregate even
    // odd numbers
    static void arrayEvenAndOdd(int[] arr, int n)
    {

        int i = -1, j = 0;
        while (j != n) {
            if (arr[j] % 2 == 0) {
                i++;

                // Swapping even and
                // odd numbers
                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
            j++;
        }

        // Printing segregated array
        for (int k = 0; k < n; k++)
            Console.Write(arr[k] + " ");
    }

    // Driver code
    static void Main()
    {
        int[] arr = { 1, 3, 2, 4, 7, 6, 9, 10 };
        int n = arr.Length;
        arrayEvenAndOdd(arr, n);
    }
}

// This code is contributed by Sam007
JavaScript
<script>
// JavaScript code to segregate even odd
// numbers in an array

// Function to segregate even odd numbers
function arrayEvenAndOdd(arr, n)
{

    let i = -1, j = 0;
    let t;
    while (j != n) {
        if (arr[j] % 2 == 0) {
            i++;

            // Swapping even and odd numbers
                let temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
        }
        j++;
    }

    // Printing segregated array
    for (let i = 0; i < n; i++)
        document.write(arr[i] + " ");
}

// Driver code

    let arr = [ 1, 3, 2, 4, 7, 6, 9, 10 ];
    let n = arr.length;
    arrayEvenAndOdd(arr, n);

// This code is contributed by Surbhi Tyagi

</script>
PHP
<?php
// PHP code to segregate even odd
// numbers in an array

// Function to segregate
// even odd numbers
function arrayEvenAndOdd($arr, $n)
{
    $i = -1;
    $j = 0;
    $t;
    while ($j != $n)
    {
        if ($arr[$j] % 2 == 0)
        {
            $i++;

            // Swapping even and
            // odd numbers
            $x = $arr[$i];
            $arr[$i] = $arr[$j];
            $arr[$j] = $x;
        }
        $j++;
    }

    // Printing segregated 
    // array
    for ($i = 0; $i < $n; $i++)
        echo $arr[$i] . " ";
}

    // Driver code
    $arr = array(1, 3, 2, 4, 7, 6, 9, 10);
    $n = sizeof($arr);
    arrayEvenAndOdd($arr, $n);

// This code is contributed by Anuj_67
?>

Output
Updated Array: 2 4 6 8 5 1 3 7 9 

Time Complexity: O(n) 
Auxiliary Space: O(1), since no extra space has been taken.



Previous Article
Next Article

Similar Reads

Hoare's vs Lomuto partition scheme in QuickSort
We have discussed the implementation of QuickSort using Lomuto partition scheme. Lomuto's partition scheme is easy to implement as compared to Hoare scheme. This has inferior performance to Hoare's QuickSort. Lomuto's Partition Scheme: This algorithm works by assuming the pivot element as the last element. If any other element is given as a pivot e
15+ min read
Quick Sort(Lomuto Partition) Visualization using JavaScript
GUI(Graphical User Interface) helps in better in understanding than programs. In this article, we will visualize Quick Sort using JavaScript. We will see how the array is being partitioned using Lomuto Partition and then how we get the final sorted array. We will also visualize the time complexity of Quick Sort. Reference: Quick SortLomuto Partitio
4 min read
Segregate even and odd numbers | Set 2
Given an array of integers, segregate even and odd numbers in the array. All the even numbers should be present first, and then the odd numbers. Examples: Input : 1 9 5 3 2 6 7 11 Output : 6 2 3 5 7 9 11 1 Input : 1 3 2 4 7 6 9 10 Output : 10 2 6 4 7 9 3 1 We have discussed one approach in Segregate Even and Odd numbers. In this post, a different s
5 min read
Segregate Even and Odd numbers | Set 2
Given an array arr[] of size N, the task is to segregate even and odd numbers. Print all even numbers first, and then odd numbers. Examples: Input: arr[] = {8, 22, 65, 70, 33, 60, 2, 34, 43, 21} Output: {8, 22, 70, 60, 2, 34, 65, 33, 43, 21} Input: arr[] = {18, 52, 37, 70, 3, 63, 2, 34} Output: {18, 52, 70, 2, 34, 37, 3, 63} Linear Approach: This p
5 min read
Segregate Even and Odd numbers
Given an array A[], write a function that segregates even and odd numbers. The functions should put all even numbers first, and then odd numbers. Example: Input = {12, 34, 45, 9, 8, 90, 3}Output = {12, 34, 8, 90, 45, 9, 3}In the output, the order of numbers can be changed, i.e., in the above example, 34 can come before 12 and 3 can come before 9. R
15+ min read
Segregate even and odd nodes in a Linked List using Deque
Given a Linked List of integers. The task is to write a program to modify the linked list such that all even numbers appear before all the odd numbers in the modified linked list. It is not needed to keep the order of even and odd nodes the same as that of the original list, the task is just to rearrange the nodes such that all even valued nodes ap
10 min read
Even numbers at even index and odd numbers at odd index
Given an array of size n containing equal number of odd and even numbers. The problem is to arrange the numbers in such a way that all the even numbers get the even index and odd numbers get the odd index. Required auxiliary space is O(1).Examples : Input : arr[] = {3, 6, 12, 1, 5, 8} Output : 6 3 12 1 8 5 Input : arr[] = {10, 9, 7, 18, 13, 19, 4,
11 min read
Minimize moves to segregate even and odd by swapping adjacent elements
Given an array arr[] of size N, the task is to find the minimum moves to segregate even and odd numbers by swapping two adjacent elements at a time. Example: Input: N = 7, arr = {3, 5, 2, 7, 9, 11, 12}Output: 3Explanation: Swap arr[2] and arr[3] to get arr = {3, 5, 7, 2, 9, 11, 12}.Move 2: Swap arr[3] and arr[4] to get arr = {3, 5, 7, 9, 2, 11, 12}
5 min read
Segregate even and odd nodes in a Linked List
Given a Linked List of integers, write a function to modify the linked list such that all even numbers appear before all the odd numbers in the modified linked list. Also, keep the order of even and odd numbers the same. Examples: Input: 17-&gt;15-&gt;8-&gt;12-&gt;10-&gt;5-&gt;4-&gt;1-&gt;7-&gt;6-&gt;NULLOutput: 8-&gt;12-&gt;10-&gt;4-&gt;6-&gt;17-
15+ min read
Count of numbers of length N having prime numbers at odd indices and odd numbers at even indices
Given a number N, the task is to calculate the count of numbers of length N having prime numbers at odd indices and odd numbers at even indices. Example: Input : N = 1Output: 5Explanation : All valid numbers length 1 are 1, 3, 5, 7, 9, here we have only 1 odd index, therefore we have 5 valid numbers. Input: N = 2Output: 20 Explanation: There are 20
5 min read
Count numbers from given range having odd digits at odd places and even digits at even places
Given two integers L and R, the task is to count numbers from the range [L, R] having odd digits at odd positions and even digits at even positions respectively. Examples: Input: L = 3, R = 25Output: 9Explanation: The numbers satisfying the conditions are 3, 5, 7, 9, 10, 12, 14, 16 and 18. Input: L = 128, R = 162Output: 7Explanation: The numbers sa
15+ min read
Find the nearest odd and even perfect squares of odd and even array elements respectively
Given an array arr[ ] of size N, the task for each array element is to print the nearest perfect square having same parity. Examples: Input: arr[ ] = {6, 3, 2, 15}Output: 4 1 4 9Explanation:The nearest even perfect square of arr[0] (= 6) is 4.The nearest odd perfect square of arr[1] (= 3) is 1.The nearest even perfect square of arr[2] (= 2) is 4The
5 min read
Count of integers in a range which have even number of odd digits and odd number of even digits
Given a range [L, R], the task is to count the numbers which have even number of odd digits and odd number of even digits. For example, 8 has 1 even digit and 0 odd digit - Satisfies the condition since 1 is odd and 0 is even.545 has 1 even digit and 2 odd digits - Satisfies the condition since 1 is odd and 2 is even.4834 has 3 even digits and 1 od
11 min read
Check if a number has an odd count of odd divisors and even count of even divisors
Given an integer N, the task is to check if N has an odd number of odd divisors and even number of even divisors. Examples: Input: N = 36Output: YesExplanation:Divisors of 36 = 1, 2, 3, 4, 6, 9, 12, 18, 36Count of Odd Divisors(1, 3, 9) = 3 [Odd]Count of Even Divisors(2, 4, 6, 12, 18, 36) = 6 [Even] Input: N = 28Output: No Naive Approach: The idea i
9 min read
Modify Binary Tree by replacing all nodes at even and odd levels by their nearest even or odd perfect squares respectively
Given a Binary Tree consisting of N nodes, the task is to replace all the nodes that are present at even-numbered levels in a Binary Tree with their nearest even perfect square and replace nodes at odd-numbered levels with their nearest odd perfect square. Examples: Input: 5 / \ 3 2 / \ 16 19 Output: 9 / \ 4 4 / \ 9 25 Explanation: Level 1: Nearest
13 min read
Absolute difference between sum of even elements at even indices & odd elements at odd indices in given Array
Given an array arr[] containing N elements, the task is to find the absolute difference between the sum of even elements at even indices &amp; the count of odd elements at odd indices. Consider 1-based indexing Examples: Input: arr[] = {3, 4, 1, 5}Output: 0Explanation: Sum of even elements at even indices: 4 {4}Sum of odd elements at odd indices: 4
5 min read
Count N-digits numbers made up of even and prime digits at odd and even positions respectively
Given a positive integer N, the task is to find the number of integers of N digits having even digits at odd indices and prime digits at even indices. Examples: Input: N = 2Output: 20Explanation:Following are the possible number of 2-digits satisfying the given criteria {20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 50, 52, 54, 56, 58, 70, 72, 74, 76, 78
12 min read
Kth element in permutation of first N natural numbers having all even numbers placed before odd numbers in increasing order
Given two integers N and K, the task is to find the Kth element in the permutation of first N natural numbers arranged such that all the even numbers appear before the odd numbers in increasing order. Examples : Input: N = 10, K = 3 Output: 6Explanation:The required permutation is {2, 4, 6, 8, 10, 1, 3, 5, 7, 9}.The 3rd number in the permutation is
9 min read
Segregate groups of first N numbers having GCD equals to 1
Given a number N. The task is to group all the numbers from 1 to N such GCD of all the numbers in each group is 1 as the number of groups must be minimized. Example: Input: N = 3 Output: 1 2 3 Explanation: gcd(1, 2, 3) = 1 Input: N = 6 Output: 1 2 3 4 5 6 Explanation: gcd(1, 2) = 1 gcd(3, 4) = 1 gcd(5, 6) = 1 Approach: As we know, the fact that GCD
6 min read
Count of N-digit Numbers having Sum of even and odd positioned digits divisible by given numbers
Given integers A, B, and N, the task is to find the total number of N-digit numbers whose sum of digits at even positions and odd positions are divisible by A and B respectively. Examples: Input: N = 2, A = 2, B = 5Output: 5Explanation:The only 2-digit numbers {50, 52, 54, 56, 58} with sum of odd-positioned digits equal to 5 and even-positioned dig
15+ min read
Python3 Program to Rotate all odd numbers right and all even numbers left in an Array of 1 to N
Given a permutation arrays A[] consisting of N numbers in range [1, N], the task is to left rotate all the even numbers and right rotate all the odd numbers of the permutation and print the updated permutation. Note: N is always even.Examples:  Input: A = {1, 2, 3, 4, 5, 6, 7, 8} Output: {7, 4, 1, 6, 3, 8, 5, 2} Explanation: Even element = {2, 4, 6
2 min read
Javascript Program to Rotate all odd numbers right and all even numbers left in an Array of 1 to N
Given a permutation arrays A[] consisting of N numbers in range [1, N], the task is to left rotate all the even numbers and right rotate all the odd numbers of the permutation and print the updated permutation. Note: N is always even.Examples:  Input: A = {1, 2, 3, 4, 5, 6, 7, 8} Output: {7, 4, 1, 6, 3, 8, 5, 2} Explanation: Even element = {2, 4, 6
2 min read
Sort all even numbers in ascending order and then sort all odd numbers in descending order
Given an array of integers (both odd and even), sort them in such a way that the first part of the array contains odd numbers sorted in descending order, rest portion contains even numbers sorted in ascending order.Examples: Input: arr[] = {1, 2, 3, 5, 4, 7, 10}Output: arr[] = {7, 5, 3, 1, 2, 4, 10} Input: arr[] = {0, 4, 5, 3, 7, 2, 1}Output: arr[]
15+ min read
Maximize the difference of sum of elements at even indices and odd indices by shifting an odd sized subarray to end of given Array.
Given an array arr[] of size N, the task is to maximize the difference of the sum of elements at even indices and elements at odd indices by shifting any subarray of odd length to the end of the array. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6}Output: 3Explanation: Initially sum of elements at even indices = 1 + 3 + 5 = 9Sum of elements at odd ind
13 min read
Make all the elements of array odd by incrementing odd-indexed elements of odd-length subarrays
Given an array arr[] of size N, the task is to make all the array elements odd by choosing an odd length subarray of arr[] and increment all odd positioned elements by 1 in this subarray. Print the count of such operations required. Examples: Input: arr[] = {2, 3, 4, 3, 5, 3, 2}Output: 2Explanation:In first operation, choose the subarray {2, 3, 4}
9 min read
Minimum removals to segregate all 0s and 1s such that count of 0s and 1s are equal
Given a binary string S of length N, the task is to find the minimum number of removals to segregate all the 0s and all the 1s such that all the 0s are before all the 1s and their count are also same. Examples: Input: S = 01001101Output: 2Explanation: If you remove the 1 at index 1 and 0 at index 6, then the string becomes 000111. Input: S = "01"Ou
7 min read
Sort and separate odd and even numbers in an Array using custom comparator
Given an array arr[], containing N elements, the task is to sort and separate odd and even numbers in an Array using a custom comparator. Example: Input: arr[] = { 5, 3, 2, 8, 7, 4, 6, 9, 1 }Output: 2 4 6 8 1 3 5 7 9 Input: arr[] = { 12, 15, 6, 2, 7, 13, 9, 4 }Output: 2 4 6 12 7 9 13 15 Approach: As we know std::sort() is used for sorting in increa
5 min read
Segregate 1s and 0s in separate halves of a Binary String
Given a binary string str of even length, consisting of equal number of 0s and 1s, the task is to segregate all 1s and 0s into separate halves by repeatedly reversing a substring. Print the minimum count of reversals required. Examples: Input: str = "01011100"Output: 2Explanation: The operations performed are as follows: "01011100" -&gt; "11101000"
5 min read
Segregate 0s and 1s in an array
You are given an array of 0s and 1s in random order. Segregate 0s on left side and 1s on right side of the array [Basically you have to sort the array]. Traverse array only once. Input array = [0, 1, 0, 1, 0, 0, 1, 1, 1, 0] Output array = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] Recommended PracticeSegregate 0s and 1sTry It! Method 1 (Count 0s or 1s) Thanks
15+ min read
Python3 Program for Segregate 0s and 1s in an array
You are given an array of 0s and 1s in random order. Segregate 0s on left side and 1s on right side of the array. Traverse array only once. Input array = [0, 1, 0, 1, 0, 0, 1, 1, 1, 0] Output array = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution. Method 1 (Count 0s or 1s) Thanks t
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg