1. 程式人生 > >counting sort

counting sort

sort int output tin public static input -- i++

public class counting_sort { //O(n) it is stable(numbers with the same value appear in the output array in the same order as they do in the input //array)
public static void sort(int[] a ){
int n = a.length;
int[] b = new int[n];
int max = a[0];
for(int i= 0;i < n;i++){
if(a[i] > max){
max = a[i];
}
}
int[] c = new int[max + 1];
for(int i= 0;i <= max ;i++){
c[i] = 0;
}
for(int i= 0;i < n;i++){
c[a[i]] = c[a[i]] + 1;
}
for(int i= 1;i <= max ;i++){
c[i] = c[i] + c[i - 1];
}
for(int i= n-1;i >= 0;i--){
b[c[a[i]] - 1] = a[i];
c[a[i]] = c[a[i]] - 1;
}
for(int i = 0;i < b.length; i++){
System.out.println(b[i] + " ");}


}

}

counting sort