思想:从低位到高位进行计数排序
基于计数排序(稳定的!)
时间复杂度 O(d*(n + k))
其中`d = log`````
k就是基数的含义
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
for (int i = 0; i <= 30; i++) {
int[] b = new int[n], c = new int[2];
for (int j = 0; j < n; j++) {
int bit = a[j] >> i & 1;
c[bit]++;
}
c[1] += c[0];
for (int j = n - 1; j >= 0; j--) {
int bit = a[j] >> i & 1;
b[c[bit] - 1] = a[j];
c[bit]--;
}
a = b;
}
for (int i = 0; i < n; i++) {
System.out.print(a[i] + " ");
}
}
}
本代码基数为二进制