Page 1 of 1

Java Partitioning program wont work properly. This is similar/identical to the dutch or three way partitioning method. A

Posted: Sat Nov 27, 2021 2:29 pm
by answerhappygod
Java Partitioning program wont work properly. This is
similar/identical to the dutch or three way partitioning method.
Anything smaller than pivot 1 should be on the left, anything
larger than pivot 2 should be on the right, and anything between
pivot 1 and pivot 2 should be in the middle.
Sometimes the program works correctly, other times it doesn't.
Ive been trying to figure out why but I havent been able to. Please
point to my error.
class Pair {
public int left, right;

public Pair(int left, int right) {
this.left = left;
this.right = right;
}
}
class partitions {

static void printArray(int[] a, int size)
{
for(int i = 0; i < size; i++)
System.out.print(a + " ");

System.out.println();
}
public static Pair
partition2Pivot(int a[], int start, int end, int pivotOne, int
pivotTwo) {
swap(a, pivotOne, start); //left pivot goes
front
pivotOne = start;
swap(a, end, pivotTwo); //right pivot goes
at the end
pivotTwo = end;



int smallpointer = start;

int bigpointer = end;

int unknown = start +1;


while(unknown <=
bigpointer)
{
if(a[unknown] >= a[pivotTwo])
{

bigpointer--;

swap(a,unknown,bigpointer);

}

if(a[unknown] <=
a[pivotOne])
{

smallpointer++;

swap(a,unknown,smallpointer);
unknown++;

}
else
{
unknown++;
}

swap(a,pivotOne,smallpointer);
pivotOne = smallpointer;

swap(a,pivotTwo,bigpointer);
pivotTwo = bigpointer;




}

return new Pair(pivotOne,pivotTwo);

}
public static void swap(int a[],int i, int j)
{

int temp = a; //method
for swaps
a = a[j];
a[j] = temp;
}
public static void main(String[] args)
{
int[] a = {1,7,91,52,15,32,31};
int n = a.length;
int pivotl = a.length-2;
int pivotr = a.length-3;

partition2Pivot(a,0,n-1,pivotl,pivotr);
System.out.println("Sorted array: ");
printArray(a, n);
}

}