对于一个int数组,请编写一个计数排序算法,对数组元素排序。
给定一个int数组A及数组的大小n,请返回排序后的数组。
测试样例:
[1,2,3,5,2,3],6
[1,2,2,3,3,5]
import java.util.*;
public class CountingSort {
public int[] countingSort(int[] A, int n) {
// write code here
if(A==null||n<2)
return A;
sort(A);
return A;
}
public void sort(int[] A){
int len = A.length;
int min = A[0];
int max = A[0];
for(int i=1;i<len;i++){
max = Math.max(max,A[i]);
min = Math.min(min,A[i]);
}
int[] count = new int[max-min+1];
for(int k=0;k<A.length;k++){
count[A[k]-min]++;
}
int index =0;
for(int j=0;j<count.length;j++){
while(count[j]-->0){
A[index++] = j+min;
}
}
}
}