Interview Questions and Answers for Java developers: How would you sort a huge array of ages?
Consider you have a huge array of numbers that represent the ages of the employees in a company and you want to write an efficient algorithm to sort this array. How would you do and what is the Big O of this algorithm?Answer: if you were sorting a regular array, you could just use the merge sort and have a great O(n . lg n) , but... Wait a minute... Can we have an even more efficient solution? Sure! This is a very specific set of data, that represents the employees ages. Since we know about the data scope, we can use this knowledge to get to an O(n) algorithm. Let's see how!
Developing the Solution:
In the known real world ages can vary between 0 and 122, but let's make our solution effective up to the next few decades or more and assume the maximum value should be 150. Since we know that the huge array is a distribution of integer values within this range, we could easily
- Count in O(n) how many employees have each age between 0 and 150, with a single loop, storing the values in a temporary array (each index is an age and each value is the count)
- Overwrite in O(n) the input array values using the counts of each age, since an array always has its indexes ordered!
For the sake of time I've written the code in JavaScript. Feel free to write it in Java or you favorite language
Read full article from Interview Questions and Answers for Java developers: How would you sort a huge array of ages?
No comments:
Post a Comment