I am confused with the optimized quick sort little help please

public static void quickSort(int []A,int p,int q){
	while(p<=q)        
	    {            
		int r = partition(A, p,q);   
		quickSort(A, p, r);            
		quickSort(A, r+1, q);        
		}
	}
static int partition(int []A, int p, int q) 

{
	
	int a=A[p];
	int lp=p-1;
	int rp=q+1;
	while(A[rp]<a)
	{
		rp=rp-1;
		while(A[rp]<a)
			lp++;
		while(A[lp]>a)
			rp--;
		if(lp>rp)
		{
			int temp=A[lp];
			A[lp]=A[rp];
			A[rp]=temp;
			
		}
		
	}
	
	return rp; 
    
      

}

It is giving me this error
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException

Why do you think the code is supposed to work?
Where did you get it? Is there any documentation for how to use it?

I wrote it I have the psedu code ,and I had to write the code,unfortunately my code is not working

Where is the ArrayIndexOutOfBoundsException?
Why is the index past the end of the array?

Do you have documentation for the algorithm that you are trying to implement?
There are zero comments in your code. I have no idea if you coded the algorithm correctly. You need to put a description of what the code does in the code as comments.

that error means you've given an invalid length for your arrays. you're trying to access an element of an array that doesn't exist.

for instance:

String[] arr = new String[3];
// create a String array which will be able to hold 3 elements, being:
// arr[0]; the first element
// arr[1];
// arr[2]; this is the last possible element. notice that the index begins at 0
// and ends at length - 1
for ( int i = 0; i < 4; i++ ){
  arr[i] = "Element index: " + i;
}

the last time you go through this loop, it'll throw an ArrayIndexOutOfBoundsException, because you will try to put a String object in element arr[3] which doesn't exist.

This article has been dead for over six months. Start a new discussion instead.