要求:对公司的员工年龄进行排序,员工人数大约万名左右,可使用常量大小的辅助空间,要求时间效率为O(n)。
实现思路:使用一个额外的辅助数组用来记录同龄的员工数目。
实现如下:
代码解读:
1)
// 初始化一个odlAge+1的数组
int[] timeOfAge = new int[oldAge + 1];
// 将数组元素都置为0
for (int i = 0; i < timeOfAge.length; i++) {
timeOfAge[i] = 0;
}
timeOfAge[]的长度为81,元素全部为0
2)age[0]=23,于是timeOfAge[23]=1; age[1]=45,于是timeOfAge[45]=1;age[ 2]=32,于是timeOfAge[32]=1;
.....age[4]=21,于是timeOfAge[21]=2;以此类推timeOfAge数组对应年龄的位置设置多少次
// 某个年龄出现了多少次,就在timeOfAge数组对应年龄的位置设置多少次
for (int j = 0; j < ages.length; j++) {
int a = ages[j];
timeOfAge[a]++;
}
3)初始,第一个for{} 中 index=0,i=20,
第二个for{} , j=0, timeOfAge[ 20]=0,所以 j < timeOfAge[i]不成立,执行i++,
于是i=21,timeOfAge[ 21]=2, 执行 ages[index] = i; 得到ages[0]=21, index++;
再得到age[1]=21; index++
int index = 0;
for (int i = youngAge; i <= oldAge; i++) {// 按照年龄从小到大依次遍历timeOfAge
for (int j = 0; j < timeOfAge[i]; j++) {// 在timeOfAge中取得各个年龄位置记录的出现次数
ages[index] = i;// 将新数组从头设置出现的年龄,已经排好序
index++;
}
}
}
import java.util.Arrays;
public class AgeSort {
public static void main(String[] args) {
int[] ages = new int[] { 23, 45, 32, 43, 21, 24, 25, 23, 22, 22, 21 };
System.out.println("原数组为:" + Arrays.toString(ages));
AgeSort as = new AgeSort();
as.sortAge(ages);
System.out.println("排序后的数组为:" + Arrays.toString(ages));
}
private void sortAge(int[] ages) {
if (ages == null || ages.length < 1) {
return;
}
int oldAge = 80;
int youngAge = 20;
// 初始化一个odlAge+1的数组
int[] timeOfAge = new int[oldAge + 1];
// 将数组元素都置为0
for (int i = 0; i < timeOfAge.length; i++) {
timeOfAge[i] = 0;
}
// 某个年龄出现了多少次,就在timeOfAge数组对应年龄的位置设置多少次
for (int j = 0; j < ages.length; j++) {
int a = ages[j];
timeOfAge[a]++;
}
int index = 0;
for (int i = youngAge; i <= oldAge; i++) {// 按照年龄从小到大依次遍历timeOfAge
for (int j = 0; j < timeOfAge[i]; j++) {// 在timeOfAge中取得各个年龄位置记录的出现次数
ages[index] = i;// 将新数组从头设置出现的年龄,已经排好序
index++;
}
}
}
}
代码也可以写成:
public static void sort(int []ages){
int oldestAge=100;
int []timesOfAges=new int[oldestAge];
int len=ages.length;
for(int i=0;i<len;i++){
timesOfAges[ages[i]]++;;
}
//排序
int index=0;
for(int i=0;i<oldestAge;i++){
for(int j=0;j<timesOfAges[i];j++){
ages[index]=i;
index++;
}
}
}
参考自:https://blog.csdn.net/a1247529789/article/details/51173993
https://blog.csdn.net/sinat_32393077/article/details/73894895