The typical problem of changing time by space is very important!
/* There may be tens of thousands of employees in age sorting, requiring the time complexity to be O (n). The idea is that the age of an employee must be within the same range, for example, 0-99, then we create an auxiliary array with a size of 100, traverse the employee's age, get an age, and add the value of the array location corresponding to the age to 1, the final array stores the number of employees of different ages and prints the array. By rowandjj2014/7/22 */# include <iostream> using namespace STD; # define max 100 void sort (INT ages [], int Len) {int temp [Max], I, j; // initialize the secondary array for (I = 0; I <Max; I ++) {temp [I] = 0;} // traverse the age array, obtain the number of employees of different ages and store them in the secondary array for (I = 0; I <Len; I ++) {temp [ages [I] ++ ;} // sort the age array int Index = 0; for (I = 0; I <Max; I ++) {for (j = 0; j <temp [I]; j ++) {ages [Index] = I; index ++ ;}} int main () {int ages [] = {, 56, 53, 11, 56, 12, 13, 5, 11, 45, 11, 67, 19, 10}; sort (ages, 25); For (INT I = 0; I <25; I ++) {cout <ages [I] <"" ;}cout <Endl; return 0 ;}
Test: