public class Main
{
public static void main (String args[])
{
int nums[]= {2, 3, 4, 5, 6, 7, 8, 9, 0, 1};
for (int index = 0; index < 10; index++)
System.out.print(" " +nums[index]);;
System.out.println();
quickSort(nums,0,9);
for (int index = 0; index < 10; index++)
System.out.print(" " +nums[index]);
System.out.println();
}
private static void swap(int a[], int lft, int rt)
{
int temp;
temp = a[lft];
a[lft] = a[rt];
a[rt] = temp;
}
public static int pivot(int firstpl, int lastpl)
{
if(firstpl >= lastpl)
return -1;
else
return firstpl;
}
private static void quickSort(int a[], int first, int last)
{
int left,right;
int pivindex = pivot(first,last);
if(pivindex >= 0)
{
left = pivindex +1;
right = last;
do
{
while ( a[left] < a[pivindex] && left <= right )
left++;
while (a[right] > a[pivindex])
right--;
if (right > left)
swap(a,left,right);
}
while(left < right);
swap (a, pivindex, right);
quickSort( a, first, right-1);
quickSort(a, right+1, last);
}
}
}
That is the code for a quick sort. Everything works right if the array’s 0 position number is “2” but if it is anything else, it throws an exception.
For example, if I put this in for array:
5 6 8 9 7 8 0 1 8 2
It gives the following error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
at Main.quickSort(Main.java:48)
at Main.quickSort(Main.java:59)
at Main.quickSort(Main.java:59)
at Main.main(Main.java:12)
Please help!
Suppose that
first = 8andlast = 9in one of the calls toquickSort(). Suppose also that a[8] > a[9]. Think about what will happen in theleft++loop…(Remember, the
a[left] < a[pivindex]part of the condition is checked before theleft <= rightpart)OK, try walking through the method:
Starting with first = 8, last = 9, I end up with pivindex = 8, left = 9, right = 9. I check the while condition:
It’s true, so I increment left. Now left = 10 and right = 9. I check the while condition again…
… and go off the end of the array. Now, if only I had checked that 10 <= 9 before looking at a[left]!
OK, if you’re still stuck I’ll just come right out and tell you. The problem in that loop is that you are trying to access
a[left]before checking ifleftis too big. You can fix the problem in one of two ways:leftnever gets bigger thanright.