(Intro to java help?) Complete the class code below and include a method named p
ID: 3706372 • Letter: #
Question
(Intro to java help?)
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
Explanation / Answer
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);
}
public static void partition(int[] ap,int n)
{
//Declaration
int i=0,j,k=0,copyofap[],ap1[],ap2[],t;
ap1 = new int[n/2]; // Memory allocation for Array for storing Lower Partition
ap2 = new int[n-n/2]; // Memory allocation for Array for storing Upper Partition
// Memory allocation for Array. As the location of elements will be changed during the patition so to retain the origional array a copy of original Array will used during the patition
copyofap=new int[n];
for(i=0;i<n;i++)
{
copyofap[i]=ap[i]; // Making a copy of origional Array
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(copyofap[j]<copyofap[i])
{t=copyofap[j];
copyofap[j]=copyofap[i];
copyofap[i]=t;
}
} //End of inner for loop
if(i<(n/2))
ap1[i]=copyofap[i]; //Storing the element in Lower Partition
else
{ap2[k]=copyofap[i]; k++;} //Storing the element in Upper Partition
} //End of outer for loop
// Display Original Array
System.out.print("Original Array:[");
for(i=0;i<n;i++)
{
System.out.print(ap[i]+",");
}
System.out.println("]");
// Display Lower Partition Array
System.out.print("Lower Partition:[");
for(i=0;i<n/2;i++)
{
System.out.print(ap1[i]+",");
}
System.out.println("]");
// Display Upper Partition Array
System.out.print("Upper Partition:[");
for(i=0;i<k;i++)
{
System.out.print(ap2[i]+",");
}
System.out.println("]");
} //end of partition
} // end of Partition class
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.