I’m trying out an implementation of QuickSort but getting an
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at com.JavaReference.QuickSort.swap(QuickSort.java:50)
at com.JavaReference.QuickSort.randPartition(QuickSort.java:20)
at com.JavaReference.QuickSort.randSort(QuickSort.java:12)
at com.JavaReference.QuickSort.randSort(QuickSort.java:13)
at com.JavaReference.QuickSort.randSort(QuickSort.java:13)
at com.JavaReference.QuickSort.randSort(QuickSort.java:13)
at com.JavaReference.QuickSort.randSort(QuickSort.java:13)
at com.JavaReference.QuickSort.randSort(QuickSort.java:8)
at com.JavaReference.QuickSort.main(QuickSort.java:59)
Here’s my source code[here.]
Im a newbie to programming so any advice on where Im going wrong would be appreciated.
EDIT:Added entire stacktrace
My suspect is line 30:Since
leftis initially 0,iwill become -1. Then on line 35 you calland bang.
OK, from the stack trace it seems my first guess was wrong.
Second guess: from the stack trace it shows that the array is partitioned 4 times, and then at the 5th attempt the exception comes. It is thrown on line 50:
ais the first parameter toswap. The call toswapon line 20 wasthus
rightis -1 at that point. This value comes from here (line 13):If
pivotis 0 at this point, shit happens. And it can become 0 since it is taken as a random value betweenleftandright, inclusive. (And actually, that is a mistake, as for effective partitioning,pivotshould fall betweenleftandright, noninclusive.) Currently, the probability ofpivotbecoming 0 increases as the leftmost partition becomes smaller. You need to introduce a check for this (or, more generally, to detect array partitions of size 1, which can’t be partitioned further), to stop the recursion in time.