/**
* 问题:对取值范围在1~100的数据集合排序
* 方法:计数排序
*
*/
public class Test09 {
public static void main(String[] args) {
int[] str = {5, 100, 100, 20, 1,30, 20};
System.out.print("原数组:");
for(int i:str)
System.out.print(i+" ");
sort(str);
System.out.println();
System.out.print("排序后的数组:");
for(int i:str)
System.out.print(i+" ");
}
public static void sort(int[] str) {
int[] arr = new int[101];
for(int i = 0; i < str.length; i++) { //将数组str中的值通过下标存储到数组arr中
arr[str[i]]++;
}
int index = 0;
for(int i = 1; i < arr.length; i++) { //将数组arr中的数有序地还原到数组str中
for(int j = 0; j < arr[i]; j++) {
str[index] = i;
index++;
}
}
}
}
计数排序:对取值范围在1~100的数据集合排序
最新推荐文章于 2020-08-07 16:48:05 发布