Problem
Given a list of characters, sort it in the non-decreasing order based on ASCII values of characters.
Example
{
"arr": ["a", "s", "d", "f", "g", "*", "&", "!", "z", "y"]
}
Output:
["!", "&", "*", "a", "d", "f", "g", "s", "y", "z"]
Solution
function sort_array(arr) {
let length = arr.length;
let result = [];
// Stores the frequency of each character of the string
let freq = new Array(256).fill(0)
// Count and store the frequency
for (let i = 0; i < length; i++) {
freq[arr[i].charCodeAt(0)]++;
}
// Store the result
for (let i = 0; i < 256; i++) {
for (let j = 0; j < freq[i]; j++) {
result.push(String.fromCharCode(i));
}
}
return result;
}
Time and Space Complexity
Time Complexity : O(256*N)
Space Complexity: O(256)