Reputation: 1920
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!
Upvotes: 1
Views: 11717
Reputation: 16364
Suppose that first = 8
and last = 9
in one of the calls to quickSort()
. Suppose also that a[8] > a[9]. Think about what will happen in the left++
loop...
(Remember, the a[left] < a[pivindex]
part of the condition is checked before the left <= right
part)
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:
while(a[9] < a[8] && 9 <= 9)
It's true, so I increment left. Now left = 10 and right = 9. I check the while condition again...
while(a[10] < a[8] && 10 <= 9)
... 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 if left
is too big. You can fix the problem in one of two ways:
left
never gets bigger than right
.Upvotes: 2
Reputation: 33954
The problem is a simple one: you're inadvertently trying to access a 10-element array with index of 10
, when the only valid indexes are 0-9.
This is happening on line #48 (or possibly 47, or 49). You're probably accidentally adding +1 to an index when you don't realize it, and exceeding the bounds of the array.
Figure out why your special case is happening, and you'll be home.
Upvotes: 2