Http://zhedahht.blog.163.com/blog/static/25411174201131184017844/
Question: If a company has tens of thousands of employees, please complete an algorithm with a time complexity of O (n) to sort the age of the employees of the company. The auxiliary space of O (1) can be used.
Analysis: Sorting is a type of question that is often mentioned during interviews. We are also familiar with many of these algorithms, such as insert sorting, Merge Sorting, Bubble sorting, and quick sorting. These sort algorithms are either O (N2), or O (NLogN. However, this question actually requires O (N). What is the mystery in this question?
This topic particularly emphasizes the sorting of the age of employees in a company. Although the number of employees is tens of thousands, the age of these tens of thousands of employees is only dozens of possibilities. People who work early usually have to wait until they are nearly 20 years old to go to work, and the average person has to retire when they reach 60 or 70 years old.
Since there are only a few dozen possibilities in total, we can easily calculate the number of employees in each age. For example, suppose there are five employees in total, whose ages are 25, 24, 26, 24, and 25. We can find out their age. Two of them are 24 years old, two are 25 years old, and one is 26 years old. The result of sorting by age is: 24, 24, 25, 25, and 26. Two 24 s, two 25 s, and one 26 s are written in the array indicating age.
To understand this idea, we can write the following code:
Void sortages (INT ages [], int length)
{
If (ages = NULL | length <= 0)
Return;
Const int oldestage = 99;
Int timesofage [oldestage + 1];
For (INT I = 0; I <= oldestage; ++ I)
Timesofage [I] = 0;
For (INT I = 0; I <length; ++ I)
{
Int age = ages [I];
If (age <0 | age> oldestage)
Throw new STD: exception ("age out of range .");
++ Timesofage [age];
}
Int Index = 0;
For (INT I = 0; I <= oldestage; ++ I)
{
For (Int J = 0; j <timesofage [I]; ++ J)
{
Ages [Index] = I;
++ Index;
}
}
}
In the above Code, the allowed range is 0 to 99 years old. The array timesofage is used to count the number of occurrences of each age. How many times a certain age appears, set this age in the array ages. This is equivalent to sorting the ages array. In this method, the auxiliary space of an integer array with a length of 100 is used for O (n) time efficiency. No matter how many people are sorted by age, the length of the auxiliary array is a fixed 100 integer, so its spatial complexity is a constant, that is, O (1 ).