import com.google.common.base.Preconditions;
import java.util.Arrays;
/**
* 借助常数大小的辅助空间来实现时间复杂度为O(n)的排序。
*/
public class SortWithAuxiliarySpace {
/**
* 将数组中的数排序,数组中存放的是学生的考试成绩。
*
* 分析:
* 1)目标数组中元素的取值范围为0~100
* 2)可以使用一个长度为101的辅助数组来存储目标数组中各元素出现的次数:辅助数组中下标为m的元素表示m在目标数组中出现的次数。
*
* @param scoreArray
*/
public static void sort(int[] scoreArray) {
Preconditions.checkArgument(null!= scoreArray && scoreArray.length > 0);
// 辅助数组
int[] timesArray = new int[101];
Arrays.stream(scoreArray).forEach(score -> {
if (score < 0 || score > 100) {
throw new IllegalArgumentException("score out of range");
}
timesArray[score]++; // 将score出现的次数加一
});
int index = 0;
for (int i = 0; i < timesArray.length; i++) { // i为辅助数组的下标,即 目标数组中的元素
for (int j = 0; j < timesArray[i]; j++) { // timesArray[i]表示i在目标数组中出现的次数。
scoreArray[index] = i;
index++;
}
}
}
public static void main(String[] args) {
int[] scoreArray = {98, 89, 45, 54, 12, 21, 36, 37, 37, 37, 99, 99, 44, 88, 88, 88, 88, 100, 0, 100, 100, 88};
sort(scoreArray);
Arrays.stream(scoreArray).forEach(score -> {
System.out.println(score);
});
}
}