计数排序(适用于1-100以内的数进行排序)
大致思路如图:
public class Countsort {
public static void main(String[] args) {
int[] a={3,5,6,4,1,2,1,2};//录入待排序数组
countArray(a);
}
public static void countArray(int[] a){
int[] countArray=new int[101];//初始化一个计数数组,系统默认所有数组元素全为0
for(int i=0;i<a.length;i++){
int index=a[i];//待排序数组的数组值对应计数数组的索引下标
countArray[index]++;//计数待排序数组元素
}
System.out.println("输出排序后的结果");
for(int index=0;index<countArray.length;index++)
for(int j=1;j<=countArray[index];j++)
System.out.print(index+" ");//计数数组记录的值为多少,就输出几次对应的索引下标
}
}
运行结果: