implementing Radix Sort on Large Arrays in Java - Unexpected Memory Usage
Could someone explain I'm working on a project and hit a roadblock. Does anyone know how to I've searched everywhere and can't find a clear answer. I'm sure I'm missing something obvious here, but I'm currently implementing a Radix Sort algorithm in Java for sorting large arrays of integers. However, I'm running into unexpected memory usage issues when sorting arrays over 1 million elements. My implementation seems to consume a lot of memory, leading to an `OutOfMemoryError` even though I'm using primitive arrays. Hereβs a snippet of my code: ```java public class RadixSort { public void sort(int[] array) { int max = getMax(array); for (int exp = 1; max / exp > 0; exp *= 10) { countingSort(array, exp); } } private void countingSort(int[] array, int exp) { int n = array.length; int[] output = new int[n]; int[] count = new int[10]; for (int i = 0; i < n; i++) { count[(array[i] / exp) % 10]++; } for (int i = 1; i < 10; i++) { count[i] += count[i - 1]; } for (int i = n - 1; i >= 0; i--) { output[count[(array[i] / exp) % 10] - 1] = array[i]; count[(array[i] / exp) % 10]--; } System.arraycopy(output, 0, array, 0, n); } private int getMax(int[] array) { int max = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] > max) { max = array[i]; } } return max; } } ``` When I run this with a million random integers, I often get the following behavior: ``` Exception in thread "main" java.lang.OutOfMemoryError: Java heap space ``` Iβm currently using the default heap settings of the JVM. Are there any optimizations I can implement to reduce memory consumption? I've tried using different data types and optimizing the counting sort, but nothing seems to help. Any advice would be greatly appreciated! For context: I'm using Java on macOS. Has anyone else encountered this? What's the best practice here? What would be the recommended way to handle this? I'm working in a CentOS environment. I'd be grateful for any help.