Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Three way partitioning of an array around a given range
Next article icon

Three way partitioning of an array around a given range

Last Updated : 20 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given an array and a range [lowVal, highVal], partition the array around the range such that array is divided in three parts. 

  • All elements smaller than lowVal come first. 
  • All elements in range lowVal to highVal come next. 
  • All elements greater than highVal appear in the end. 

The individual elements of the three sets can appear in any order.

Examples;

Input: arr[] = {1, 14, 5, 20, 4, 2, 54, 20, 87, 98, 3, 1, 32}  , lowVal = 14 , highVal = 20
Output: arr[] = {1, 5, 4, 2, 1, 3, 14, 20, 20, 98, 87, 32, 54}
Explanation: all elements which are less than 14 are present in the range of 0 to 6
                       all elements which are greater than 14 and less than 20 are present in the range of 7 to 8
                       all elements which are greater than 20 are present in the range of 9 to 12        

Input: arr[] = {1, 14, 5, 20, 4, 2, 54, 20, 87, 98, 3, 1, 32} , lowVal = 20 , highVal = 20     
Output: arr[] = {1, 14, 5, 4, 2, 1, 3, 20, 20, 98, 87, 32, 54} 

Recommended Problem
Three way partitioning
Solve Problem

The idea is based on Dutch National Flag based QuickSort. We traverse the given array of elements from left. We keep track of two pointers, first to store next position of smaller element (smaller than range) from beginning, and second to store next position of greater element from end. while traversing the array use these two pointers to place elements according to their range.

Follow the steps mentioned below to implement the idea:

  • Create two variables start and end to store the index of the vacant place to store the elements according to their range.
  • Traverse the array from 0 to end.
  • If an element is less than lowVal then swap it with the element present at index start and increase the value of start by 1.
  • If an element is greater than highVal then swap it with the element present at index end and decrease the value of end by 1.
  • Print the array.                                                                                                                                                                                                                                        

Below is the implementation of the above approach:

C++
// C++ program to implement three way partitioning // around a given range. #include <iostream> using namespace std;  // Partitions arr[0..n-1] around [lowVal..highVal] void threeWayPartition(int arr[], int n, int lowVal,                        int highVal) {     // Initialize next available positions for     // smaller (than range) and greater elements     int start = 0, end = n - 1;      // Traverse elements from left     for (int i = 0; i <= end;) {         // If current element is smaller than         // range, put it on next available smaller         // position.         if (arr[i] < lowVal) {             // if i and start are same in that case we can't             // swap swap only if i is greater than start             if (i == start) {                 start++;                 i++;             }             else                 swap(arr[i++], arr[start++]);         }          // If current element is greater than         // range, put it on next available greater         // position.         else if (arr[i] > highVal)             swap(arr[i], arr[end--]);          else             i++;     } }  // Driver code int main() {     int arr[]         = { 1, 14, 5, 20, 4, 2, 54, 20, 87, 98, 3, 1, 32 };     int n = sizeof(arr) / sizeof(arr[0]);      threeWayPartition(arr, n, 10, 20);      cout << "Modified array \n";     for (int i = 0; i < n; i++)         cout << arr[i] << " "; } 
Java
// Java program to implement three way partitioning // around a given range. import java.io.*;  class GFG {      // Partitions arr[0..n-1] around [lowVal..highVal]     public static void     threeWayPartition(int[] arr, int lowVal, int highVal)     {          int n = arr.length;          // Initialize ext available positions for         // smaller (than range) and greater elements         int start = 0, end = n - 1;          // Traverse elements from left         for (int i = 0; i <= end;) {              // If current element is smaller than             // range, put it on next available smaller             // position.              if (arr[i] < lowVal) {                  int temp = arr[start];                 arr[start] = arr[i];                 arr[i] = temp;                 start++;                 i++;             }              // If current element is greater than             // range, put it on next available greater             // position.             else if (arr[i] > highVal) {                  int temp = arr[end];                 arr[end] = arr[i];                 arr[i] = temp;                 end--;             }              else                 i++;         }     }      public static void main(String[] args)     {          int arr[] = { 1,  14, 5,  20, 4, 2, 54,                       20, 87, 98, 3,  1, 32 };          threeWayPartition(arr, 10, 20);          System.out.println("Modified array ");         for (int i = 0; i < arr.length; i++) {             System.out.print(arr[i] + " ");         }     } }  // This code is contributed by Dheerendra Singh 
Python3
# Python3 program to implement three way # partitioning around a given range.  # Partitions arr[0..n-1] around [lowVal..highVal]   def threeWayPartition(arr, n, lowVal, highVal):      # Initialize ext available positions for     # smaller (than range) and greater elements     start = 0     end = n - 1     i = 0      # Traverse elements from left     while i <= end:          # If current element is smaller than         # range, put it on next available smaller         # position.         if arr[i] < lowVal:               arr[i], arr[start] = arr[start], arr[i]             i += 1             start += 1          # If current element is greater than         # range, put it on next available greater         # position.         elif arr[i] > highVal:               arr[i], arr[end] = arr[end], arr[i]             end -= 1          else:             i += 1  # Driver code if __name__ == "__main__":     arr = [1, 14, 5, 20, 4, 2, 54,             20, 87, 98, 3, 1, 32]     n = len(arr)      threeWayPartition(arr, n, 10, 20)      print("Modified array")     for i in range(n):         print(arr[i], end = " ")  # This code is contributed by # sanjeev2552 
C#
// C# program to implement three way // partitioning around a given range. using System;  class GFG {      // Partitions arr[0..n-1]     // around [lowVal..highVal]     public static void     threeWayPartition(int[] arr, int lowVal, int highVal)     {         int n = arr.Length;          // Initialize ext available positions for         // smaller (than range) and greater elements         int start = 0, end = n - 1;          // Traverse elements from left         for (int i = 0; i <= end;) {              // If current element is smaller than             // range, put it on next available smaller             // position.              if (arr[i] < lowVal) {                  int temp = arr[start];                 arr[start] = arr[i];                 arr[i] = temp;                 start++;                 i++;             }              // If current element is greater than             // range, put it on next available greater             // position.             else if (arr[i] > highVal) {                  int temp = arr[end];                 arr[end] = arr[i];                 arr[i] = temp;                 end--;             }              else                 i++;         }     }      // Driver code     public static void Main()     {         int[] arr = { 1,  14, 5,  20, 4, 2, 54,                       20, 87, 98, 3,  1, 32 };          threeWayPartition(arr, 10, 20);          Console.WriteLine("Modified array ");         for (int i = 0; i < arr.Length; i++) {             Console.Write(arr[i] + " ");         }     } }  //  
JavaScript
<script>  // JavaScript program to implement three  // way partitioning around a given range.  // Partitions arr[0..n-1] around [lowVal..highVal] function threeWayPartition(arr, n, lowVal, highVal) {          // Initialize ext available positions for     // smaller (than range) and greater elements     let start = 0, end = n - 1;      // Traverse elements from left     for(let i = 0; i <= end;)     {                  // If current element is smaller than         // range, put it on next available smaller         // position.         if (arr[i] < lowVal)         {               let temp = arr[start];             arr[start] = arr[i];             arr[i] = temp;             start++;             i++;         }          // If current element is greater than         // range, put it on next available greater         // position.         else if(arr[i] > highVal)         {                  let temp = arr[end];             arr[end] = arr[i];             arr[i] = temp;             end--;         }         else             i++;     } }  // Driver code let arr = [ 1, 14, 5, 20, 4, 2, 54,              20, 87, 98, 3, 1, 32 ]; let n = arr.length;  threeWayPartition(arr, n, 10, 20);  document.write("Modified array <br>"); for(let i = 0; i < n; i++)     document.write(arr[i] + " ");  // This code is contributed by Surbhi Tyagi.  </script> 

Output
Modified array  1 5 4 2 1 3 14 20 20 98 87 32 54 

Time Complexity: O(N) 
Auxiliary Space: O(1)


Next Article
Three way partitioning of an array around a given range

K

kartik
Improve
Article Tags :
  • DSA
  • Arrays
  • Yahoo
  • array-rearrange
Practice Tags :
  • Yahoo
  • Arrays

Similar Reads

    Three way partitioning around an element
    Given an array arr[] of integers and a value pivot, the task is to partition the array around the pivot such that array is divided in three parts. All elements smaller than pivot come first. All elements equal to pivot come next. All elements greater than pivot appear in the end. The individual elem
    14 min read
    Three way partitioning of an Array without changing the relative ordering
    Given an array and a range [lowVal, highVal], partition the array around the range such that the array is divided into three parts. All elements smaller than lowVal come first. All elements in range lowVal to highVal come next. All elements greater than highVVal appear in the end. The relative order
    9 min read
    Minimize the cost of partitioning an array into K groups
    Given an array arr[] and an integer K, the task is to partition the array into K non-empty groups where each group is a subarray of the given array and each element of the array is part of only one group. All the elements in a given group must have the same value. You can perform the following opera
    15+ min read
    Count all Arrays within a Range and Divisible by 3
    Given three integers n,l,r, the task is to determine the count of such arrays that follow the below two conditions: All the elements of the array are between l to r (inclusive) The sum of all the elements is divisible by 3.Since the answer can be very long, print the remainder when the result is div
    9 min read
    Find the missing elements from 1 to M in given N ranges
    Given N segments as ranges [L, R] where ranges are non-intersecting and non-overlapping. The task is to find all number between 1 to M that doesn't belong to any of the given ranges. Examples: Input : N = 2, M = 6 Ranges: [1, 2] [4, 5] Output : 3, 6 Explanation: Only 3 and 6 are missing from the abo
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences