Introduction
You have a large, potentially enormous array of objects in random order. You want to divide the array in half, with the lower half containing objects that match the condition and the upper half containing objects that do not. An array's partitioning is the name for this process.
We are going to discuss an array partitioning problem in this article.
Also See, Array Implementation of Queue and Rabin Karp Algorithm
Problem Statement
Partition an array around a range [startVal, endVal] so that it is divided into three parts.
- All elements with a smaller startval value are prioritized.
- Following that are all elements in the range startval to endval.
- In the end, all elements with a value greater than endval appear.
Sample Examples
Consider the following array:
3, 5, 2, 7, 6, 4, 2, 8, 8, 9, 0
A two-part structure Quick Sort would choose a value, such as 4, and sort the array so that every element greater than 4 is on one side and every element less than 4 is on the other. As follows:
3, 2, 0, 2, 4, | 8, 7, 8, 9, 6, 5
A three-part structure Quick Sort would divide the array into two partitions based on two values. Let's go with 4 and 7:
3, 2, 0, 2, | 4, 6, 5, 7, | 8, 8, 9
It's merely a minor variation on the standard quicksort.
Approach 1( Naive)
Sorting the array can help with this. However, it will take nlogn time to do so. (where n denotes the array's length).
Algorithm
-
Initialize the array's elements after declaring an array of size n.
-
Now, initialise the range's lower and upper bounds and save them in the variables low and high, respectively.
-
Sort the array now that it has been partitioned by sorting.
Note: The array's order cannot be preserved by this algorithm.
Syntax:
Sort(arrayname, arrayname+sizeofarray) ;
Elements are sorted in the order of low to high.
Implementation
#include<bits/stdc++.h>
using namespace std;
int main(){
int arr[] ={23,5,18,10,20,89 };
int n =sizeof(arr)/sizeof(int);
int low=0,high=4;
sort(arr,arr+n);
for(int i=0;i<n;i++){
cout<<arr[i]<<" ";
}
return 0;
}
Output
5 10 18 20 23 89
Complexity Analysis
Time Complexity: O(n^3), as the array is traversed by three nested loops.
Space Complexity: O(1), as we are not using any extra space.