Partition算法代码触发java.lang.ArrayIndexOutOfBoundsException:10的修正方案咨询
java.lang.ArrayIndexOutOfBoundsException: 10 in Your Partition Algorithm Let's break this down clearly: that error means your code is trying to access index 10 of an array that only has valid indices from 0 to 9 (since Java arrays use 0-based indexing). Partition algorithms are super prone to off-by-one bugs with pointer ranges, so let's walk through the most common fixes:
Check your initial pointer bounds
A super common mistake is setting thehighpointer to the array's length instead ofarray.length - 1. For example, if your array has 10 elements (indices 0-9), usinghigh = array.lengthstarts your right pointer at index 10 immediately—boom, that's your exception.
Wrong initialization:int low = 0; int high = array.length; // ❌ This points to index 10 for a 10-element arrayFixed version:
int low = 0; int high = array.length - 1; // ✅ Correctly targets the last valid index (9)Add boundary checks to your pointer loops
When moving your left/right pointers to find elements to swap, you need to make sure you don't run past the valid array bounds. Without these checks, your pointers can creep pasthighor belowlowand hit index 10.
Broken loop logic:while (array[left] <= pivot) left++; // No check to stop at high while (array[right] > pivot) right--; // No check to stop at lowFixed loops:
while (left <= high && array[left] <= pivot) left++; // Stop before exceeding high while (right >= low && array[right] > pivot) right--; // Stop before going below lowValidate your pivot selection and swap logic
If you're picking a pivot (like the last element), make sure any swaps or recursive calls don't reference out-of-bounds indices. For example, when recursively calling your partition method, ensure you passright - 1orleft + 1instead of values that go beyond the array's valid range.Debug with print statements
If you're still stuck, add quick printouts to track your pointer values during execution. This will show you exactly whenleftorrightjumps to 10:System.out.printf("Left: %d, Right: %d, Array Length: %d%n", left, right, array.length);
The core rule here is never access an array index outside 0 to array.length - 1. Partition algorithms live or die by precise boundary handling, so double-check every place you reference an array index—those off-by-one errors are easy to miss but simple to fix once you spot them.
内容的提问来源于stack exchange,提问作者B. Rodriguez

