CodexBloom - Programming Q&A Platform

Problems with Recursive QuickSort Implementation in Java - StackOverflowError on Large Inputs

πŸ‘€ Views: 0 πŸ’¬ Answers: 1 πŸ“… Created: 2025-07-23
algorithm quicksort recursion Java

I've looked through the documentation and I'm still confused about I'm working with a `StackOverflowError` when running my recursive QuickSort implementation on larger inputs. I'm using Java 11 and have implemented the algorithm as follows: ```java public class QuickSort { public static void quickSort(int[] array, int low, int high) { if (low < high) { int pivotIndex = partition(array, low, high); quickSort(array, low, pivotIndex - 1); quickSort(array, pivotIndex + 1, high); } } private static int partition(int[] array, int low, int high) { int pivot = array[high]; int i = (low - 1); for (int j = low; j < high; j++) { if (array[j] <= pivot) { i++; int temp = array[i]; array[i] = array[j]; array[j] = temp; } } int temp = array[i + 1]; array[i + 1] = array[high]; array[high] = temp; return i + 1; } } ``` I've been testing the algorithm with arrays of size 10,000 and larger, and I consistently run into this scenario. I suspect it might be related to the depth of recursion, especially since the input seems to affect the pivot selection in the partitioning step. I've tried implementing a random pivot selection strategy, but it hasn't alleviated the question significantly. For example, here’s how I attempted to implement it: ```java private static int partition(int[] array, int low, int high) { int randomIndex = low + (int)(Math.random() * (high - low)); swap(array, randomIndex, high); int pivot = array[high]; // Rest of partition code... } ``` Despite these changes, the behavior continues. In addition, I tried increasing the stack size using the JVM argument `-Xss2m`, but that only extends the limit without truly solving the underlying question. I'm interested in any best practices or design patterns that could guide to refactor this implementation to handle larger arrays more efficiently. Any suggestions or insights would be greatly appreciated! I'm working on a API that needs to handle this. Is there a better approach?