Java Index Array out of Bounds Error for partitioning method. The left pointer seems to be going out of bounds but I can

Business, Finance, Economics, Accounting, Operations Management, Computer Science, Electrical Engineering, Mechanical Engineering, Civil Engineering, Chemical Engineering, Algebra, Precalculus, Statistics and Probabilty, Advanced Math, Physics, Chemistry, Biology, Nursing, Psychology, Certifications, Tests, Prep, and more.
Post Reply
answerhappygod
Site Admin
Posts: 899603
Joined: Mon Aug 02, 2021 8:13 am

Java Index Array out of Bounds Error for partitioning method. The left pointer seems to be going out of bounds but I can

Post by answerhappygod »

Java Index Array out of Bounds Error for partitioning method.
The left pointer seems to be going out of bounds but I cant figure
out how to fix it.
import java.io.*;
public class Tester {
static int ran = 93;
public static void main(String[] args) throws IOException {
int[] num = new int[50];
int[] numSave = new int[50];
for (int n = 10; n <= 20; n += 10) {
fillRandom(num, n);
for (int i = 0; i < n; i++) {
numSave = num;
}
System.out.print(" Given array. ");
printArray(numSave, n);
for (int j = 0; j < n; j++) {
for (int i = 0; i < n; i++) {
num = numSave;
}
System.out.print(" pivot: ");
if (num[j] < 10)
System.out.print(" ");
System.out.print(num[j] + " ");
PartitionMethods.partition(num, 0, n - 1, j); //calls
partition
printArray(num, n);
}
System.out.println();
}
System.out.println();
}
public static void fillRandom(int a[], int n) {
for (int i = 0; i < n; i++) {
ran = (ran * 101 + 103) % 1000003;
a = ran / 20000;
}
}
public static void printArray(int a[], int n) {
for (int i = 0; i < n; i++) {
if (a < 10)
System.out.print(" ");
System.out.print(a + " ");
}
System.out.println();
}
}
class PartitionMethods
{
public static void swap(int a[],int i, int j)
{

int temp = a; //method
for swaps
a = a[j];
a[j] = temp;
}

public static int partition(int a[], int start, int end, int
pivot) //left pointer for this one is
messed
{
swap(a, start, pivot); //swap pivot to
start
pivot = start;

int LFPntr = start+1; // lfpt is at
index 1, after the pivot
int RTPntr = end; // rtpt
is at the end of the array
while(LFPntr < RTPntr)
{
while(a[RTPntr]
> a[pivot])
{ // if RTPT is larger
than pivot, move pointer down

RTPntr--;
}
while(a[LFPntr] <
a[pivot])
{ //if LFPT is smaller
than pivot, move pointer up

LFPntr++;

}
if(start <=
end)

swap(a,LFPntr, RTPntr);
}
if (a[RTPntr]<a[pivot])
//swaps the pivot back into correct place
{

swap(a,pivot,RTPntr);
pivot = RTPntr;


}
else
{

swap(a,pivot,RTPntr+1);
pivot = RTPntr+1;
}
return pivot;
}
}
Join a community of subject matter experts. Register for FREE to view solutions, replies, and use search function. Request answer by replying!
Post Reply