CodexBloom - Programming Q&A Platform

Implementing a Counting Sort Algorithm in Java for Large Ranges: Handling Edge Cases

👀 Views: 67 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-03
algorithm sorting performance java Java

I keep running into I'm experimenting with I'm trying to implement a counting sort algorithm in Java for a dataset that has a very large range of integer values, specifically from `-100000` to `100000`. I understand that counting sort is generally effective for smaller ranges, but I'm concerned about the memory usage and performance when handling such a wide range. I started by defining an array to hold the counts, but I quickly ran into issues with negative indices. My current approach looks like this: ```java public class CountingSort { public static void countingSort(int[] arr) { int min = -100000; int max = 100000; int range = max - min + 1; // Initialize count array int[] count = new int[range]; // Store the count of each number for (int num : arr) { count[num - min]++; } // Reconstruct the sorted array int index = 0; for (int i = 0; i < count.length; i++) { while (count[i]-- > 0) { arr[index++] = i + min; } } } } ``` However, when I run this code with an input like `[100000, -99999, -100000, 99999]`, I get an `ArrayIndexOutOfBoundsException`. I realize that the way I handle the count array might be causing this issue, particularly when dealing with the minimum value. How can I efficiently handle these negative values in the counting sort without running into memory issues or exceptions? Additionally, what are the best practices for optimizing the performance of this algorithm in terms of both time and space complexity? My team is using Java for this microservice. I'd love to hear your thoughts on this. I've been using Java for about a year now.