實作一個排序算法,要求時間效率為 O(n)
——來源于《劍指offer》
要求:
- 樣本為公司幾萬名員工(數字的大小是在一個較小的範圍之内)
- 隻允許使用常量大小輔助空間,不得超過
O(n)
代碼實作:
package com.qianyu.jianzhioffer.sort;
/**
* @author lijing
* @date 2019-07-21-10:47
* @discroption 對公司的員工年齡進行排序
*/
public class SortAges {
private final int MAX_AGE = 99;
private void solution(int[] ages) {
if (ages == null || ages.length == 0) {
return;
}
int[] timesOfAge = new int[MAX_AGE + 1];
for (int i = 0; i < ages.length; i++) {
int age = ages[i];
if (age < 0 || age > MAX_AGE) {
throw new RuntimeException("age out of range");
}
timesOfAge[age]++;
}
int index = 0;
for (int i = 1; i <= MAX_AGE; i++) {
for (int j = 0; j < timesOfAge[i]; j++) {
ages[index] = i;
++index;
}
}
}
}