by ploggingdev · 10y ago · 0 comments
/ build the boolean result array
boolean[] result = new boolean[array.length];
for(int index = 0; index < array.length; index++) {
int num = array[index];
result[num] = true;
}
The result array is the same size as the original array.But when you do:
int num = array[index];
result[num] = true;
The index being referenced in the result array is dependent on the value of num. So if num is greater than or equal to the length of the array, it throws an ArrayOutOfBoundsException. And what happens when you try sorting an array with elements having the same value?Eg- try sorting {10,5,9}
Unrelated: HN needs to allow highlighting code inline.
boolean[] result = new boolean[Math.max(array)];
Consider sorting an array of 2 large integers {65000,30000}. To sort this array, the result array will be initialized with 65000 elements. Very inefficient.
You should look into bucketsort. That allows you to sort in finite universes in Theta(n+k) without allocating huge arrays for large integers.