In: Computer Science
Complete the class code below and include a method named partition which takes an integer array and a partition integer as parameters and then partitions the original array into two new arrays where elements of the first array are all less than or equal to the partition integer and the second array are all greater than the partition integer.
The method should print the original array, followed by the lower partition and finally the upper partition. Nothing should be returned by the method.
For example, given int[ ] arr = {1, 45, 16, 7, 39, 6, 5, 11, 72, 31, 15} a method call to partition(arr, 11) should output:
[1, 45, 16, 7, 39, 6, 5, 11, 72, 31, 15]
[1, 5, 6, 7, 11]
[15, 16, 31, 39, 45, 72]
public class Partition {
public static void main(String[] args) {
int[] arrayToPartition = {1, 45, 16, 7, 39, 6, 5, 11, 72, 31, 15};
int partitionNumber = 11;
partition(arrayToPartition, partitionNumber);
}
// your method code here
} // end of Partition class
The explanation is done in the code itself. If you have any queries write a comment. If you have understood upvote thank you.
SOLUTION:
public class Partition {
public static void partition(int arr[],int num){
//declare two arrays to store the lower and higher elements
//here i have given its length equal to the length of the
original
//array so that shere should not be any exceptions when the the
given element is maximum//element in that case
int lowerArray[]=new int[arr.length];
int upperArray[]=new int[arr.length];
//pointer for index of the two arrays
int up=0,lp=0;
System.out.print("Original Array ");
//iterate through all the elements
for(int i=0;i<arr.length;i++){
//check for great and less condition and place them in the
appropriate arrays and update their index
if(arr[i]<=num){
lowerArray[lp]=arr[i];
lp=lp+1;
}else{
upperArray[up]=arr[i];
up=up+1;
}
//i am printing the original array here itself
System.out.print(" "+arr[i]+" ");
}
//here print donot take new line while println takes it
//print all the data by checking the indexes of the higher and
lower arrays
System.out.println("");
System.out.print("Lower array elements ");
for(int i=0;i<lp;i++){
System.out.print(" "+lowerArray[i]+" ");
}
System.out.println("");
System.out.print("Upper Array ");
for(int i=0;i<up;i++){
System.out.print(" "+upperArray[i]+" ");
}
}
public static void main(String[] args) {
int[] arrayToPartition = {1, 45, 16, 7, 39, 6, 5, 11, 72, 31,
15};
int partitionNumber = 11;
partition(arrayToPartition, partitionNumber);
}
} // end of Partition class
CODE AND OUTPUT: