CodexBloom - Programming Q&A Platform

Inconsistent Results with Quick Sort on Large Arrays in Java - Stack Overflow scenarios

πŸ‘€ Views: 34 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-11
java algorithm quicksort recursion Java

I'm dealing with This might be a silly question, but Hey everyone, I'm running into an issue that's driving me crazy... Hey everyone, I'm running into an issue that's driving me crazy. I'm having trouble with my Quick Sort implementation in Java, particularly when sorting large arrays. My implementation generally sorts smaller arrays correctly, but with larger datasets, I'm working with a StackOverflowError. Here’s my code: ```java public class QuickSort { public void sort(int[] array, int low, int high) { if (low < high) { int pivotIndex = partition(array, low, high); sort(array, low, pivotIndex - 1); sort(array, pivotIndex + 1, high); } } private 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++; swap(array, i, j); } } swap(array, i + 1, high); return i + 1; } private void swap(int[] array, int i, int j) { int temp = array[i]; array[i] = array[j]; array[j] = temp; } } ``` When I run this with an array of size 10,000, it throws a `StackOverflowError`. I suspect it might be due to the depth of recursion when the partitioning is unbalanced. To mitigate this, I tried switching to a median-of-three pivot selection, but it didn't resolve the scenario. Here’s the updated partition method: ```java private int partition(int[] array, int low, int high) { int middle = low + (high - low) / 2; int pivot = medianOfThree(array, low, middle, high); // ... (rest of the partition logic) } private int medianOfThree(int[] array, int low, int middle, int high) { if (array[low] > array[middle]) swap(array, low, middle); if (array[low] > array[high]) swap(array, low, high); if (array[middle] > array[high]) swap(array, middle, high); return array[middle]; } ``` I also checked for already sorted arrays or arrays with many duplicate values, but even with random input, it fails. I'm running this on Java 11. Any insights on how to improve the performance or avoid the stack overflow? Should I consider switching to an iterative version of Quick Sort? My development environment is Windows. Is there a better approach? How would you solve this? I've been using Java for about a year now. For reference, this is a production REST API. Is there a better approach?