Counting Sort Implementation
Imagine you have an array like this (note that the array has duplicates, and includes 0 and k):
a = [ 4, 64, 200, 42, 56, 22, 1, 64, 0, 161, 200, 0, 42 ]
What you know about this array is
Values are integers
Values are non-negative and less than some number, for example:
0 <= value <= k, where k is an integer
To start, can you please write some code to sort this array using any algorithm you want and not using the library functions. Let’s assume there are no space/time requirements. This part of the coding interview is not about the algorithms, our goal is to write some code and get it running.
1 public void bucketSort(int[] arr) { 2 if (arr == null || arr.length < 1) return; 3 Map<Integer, Integer> itemToCountMapping = new HashMap<>(); 4 int min = arr[0]; 5 int max = arr[0]; 6 7 for (int value : arr) { 8 min = Math.min(min, value); 9 max = Math.max(max, value); 10 itemToCountMapping.put(value, itemToCountMapping.getOrDefault(value, 0) + 1); 11 } 12 13 int index = 0; 14 for (int i = min; i <= max; i++) { 15 int count = itemToCountMapping.getOrDefault(i, 0); 16 for (int j = 1; j <= count; j++) { 17 arr[index] = i; 18 index++; 19 } 20 } 21 }