两种数组排序方法:Shell sort触发ArrayIndexOutOfBoundsException:0错误求助
Hey there! Let's figure out why your Shell Sort is throwing that ArrayIndexOutOfBoundsException: 0 error. This issue almost always boils down to your code trying to access an array position that doesn't exist—and index 0 specifically points to a few common pitfalls we can fix quickly.
Common Culprits & Fixes
1. Missing Boundary Checks for Empty/Small Arrays
If a user enters a number count of 0 (or accidentally inputs an invalid value that gets converted to 0), you'll create an array of length 0. When your Shell Sort tries to access arr[0] in this case, it'll immediately throw the error.
Fix: Add a guard clause at the start of your Shell Sort method to handle empty or single-element arrays (they don't need sorting anyway):
public static void shellSort(int[] arr) { // Exit early if array is null, empty, or already sorted if (arr == null || arr.length <= 1) { return; } // Rest of your Shell Sort logic here }
Also, add validation in your input-handling code to prevent users from entering a non-positive number count:
Scanner scanner = new Scanner(System.in); System.out.println("Enter number count:"); int count = scanner.nextInt(); if (count <= 0) { System.out.println("Number count must be greater than 0!"); scanner.close(); return; } // Proceed to create array and read input
2. Invalid Initial Gap Calculation
Shell Sort relies on starting with a valid gap value (usually half the array length) and reducing it until it reaches 0. If your initial gap is calculated incorrectly (e.g., starting at 0 instead of arr.length / 2), your loop logic will try to access array indices using a gap of 0—leading to unexpected index access.
Correct Gap Initialization Example:
int n = arr.length; int gap = n / 2; // Start with gap = half the array length while (gap > 0) { // Perform insertion sort for this gap for (int i = gap; i < n; i++) { int temp = arr[i]; int j; // Shift elements to find the correct position for temp for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) { arr[j] = arr[j - gap]; } arr[j] = temp; } gap /= 2; // Reduce gap by half each iteration }
Full Working Shell Sort Example
Putting it all together, here's a robust Shell Sort implementation that avoids the index error:
import java.util.Scanner; public class SortProgram { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Get sort method choice System.out.println("Choose sort method: 1. Basic Sort 2. Shell Sort"); int choice = scanner.nextInt(); // Get and validate number count System.out.println("Enter number count:"); int count = scanner.nextInt(); if (count <= 0) { System.out.println("Invalid count! Please enter a positive number."); scanner.close(); return; } // Read numbers into array int[] nums = new int[count]; System.out.println("Enter " + count + " numbers:"); for (int i = 0; i < count; i++) { nums[i] = scanner.nextInt(); } // Execute sort if (choice == 1) { // Your working basic sort implementation here basicSort(nums); } else if (choice == 2) { shellSort(nums); } else { System.out.println("Invalid choice!"); scanner.close(); return; } // Print sorted result System.out.println("Sorted array:"); for (int num : nums) { System.out.print(num + " "); } scanner.close(); } public static void basicSort(int[] arr) { // Your existing working basic sort code int n = arr.length; for (int i = 0; i < n-1; i++) { int minIdx = i; for (int j = i+1; j < n; j++) { if (arr[j] < arr[minIdx]) { minIdx = j; } } int temp = arr[minIdx]; arr[minIdx] = arr[i]; arr[i] = temp; } } public static void shellSort(int[] arr) { if (arr == null || arr.length <= 1) { return; } int n = arr.length; int gap = n / 2; while (gap > 0) { for (int i = gap; i < n; i++) { int temp = arr[i]; int j; for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) { arr[j] = arr[j - gap]; } arr[j] = temp; } gap /= 2; } } }
Key Takeaway
The ArrayIndexOutOfBoundsException: 0 is almost certainly happening because your code wasn't handling empty arrays or had an invalid gap starting value. Adding boundary checks and fixing the gap initialization should resolve the issue completely.
内容的提问来源于stack exchange,提问作者Eriks

