Three way partitioning of an array around a given range

Question -
Given an array and a range [lowValhighVal], partition the array around the range such that array is divided in three parts.
1) All elements smaller than lowVal come first.
2) All elements in range lowVal to highVVal come next.
3) All elements greater than highVVal appear in the end.
The individual elements of three sets can appear in any order.
Example - 
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}

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} 

Approach - 
first we print numbers less than low value and then print numbers betweeen range and then print numbers greater than high value.

Implementation - 
//Three way partitioning of the array around an given range with time complexity - O(3*n)
#include<iostream>
using namespace std;
void threewaypartition(int arr[],int n,int low,int high)
{
    for(int i=1;i<=3;i++){
        if(i==1){
            for(int j=0;j<n;j++){
                if(arr[j]<low)
                    cout<<arr[j]<<", ";
            }
        }
        else if(i==2){
            for(int j=0;j<n;j++){
                if(arr[j]>=low&&arr[j]<=high)
                    cout<<arr[j]<<", ";
            }
        }
        else {
            for(int j=0;j<n;j++){
                if(arr[j]>high)
                    cout<<arr[j]<<", ";
            }
        }
    }
}
int main()
{
    int n;
    cout<<"Enter the number of elements : ";cin>>n;
    int arr[n];
    cout<<"Enter elements : "<<endl;
    for(int i=0;i<n;i++)
        cin>>arr[i];
    int low,high;
    cout<<"Enter low and high value : "<<endl;
    cin>>low>>high;

    threewaypartition(arr,n,low,high);
    return 0;
}
Time complexity - O(3*n)

Comments