In: Computer Science
public class Problem1 {
public static void partition(int[] A)
{
/*Rearrange the array to have the
following property:
Suppose the first element in the
original array has the value x.
In the new array, suppose that x is
in position i, that is data[i] = x.
Then, data[j] <= x for all j
< I and data[j] > x for all j > i.
Thus, informally, all the values to
the "left" of x are less than (or equal to) x
and all values to the right are
larger than x.
*/
// Complete this method
}
public static void main(String[] args) {
// TODO Auto-generated method
stub
int[] A = {4,3,9,2,7,6,5};
System.out.println("Before
partition:");
for(int i = 0; i < A.length;
i++)
{
System.out.print(A[i] + " ");
}
partition(A);
System.out.println("After
partition:");
System.out.println("Before
partition:");
for(int i = 0; i < A.length;
i++)
{
System.out.print(A[i] + " ");
}
}
}
CODE:
public class Main
{
public static void partition(int[] A)
{
/*Rearrange the array to have the following property:
Suppose the first element in the original array has the value
x.
In the new array, suppose that x is in position i, that is data[i]
= x.
Then, data[j] <= x for all j < I and data[j] > x for all j
> i.
Thus, informally, all the values to the "left" of x are less than
(or equal to) x
and all values to the right are larger than x.
*/
int i=1;
for (int j = 1; j < A.length; ++j)
{
if (A[j] <= A[0])
{
int temp=A[i];
A[i]=A[j];
A[j]=temp;
++i;
}
}
int temp=A[i-1];
A[i-1]=A[0];
A[0]=temp;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] A = {4,3,9,2,7,6,5};
System.out.println("Before partition:");
for(int i = 0; i < A.length; i++)
{
System.out.print(A[i] + " ");
}
partition(A);
System.out.println("\nAfter partition:");
for(int i = 0; i < A.length; i++)
{
System.out.print(A[i] + " ");
}
}
}
OUTPUT: