计数排序
- 基本思想,找到数组中的最大值val,建立一个val+1大小的数组bucket,遍历原数组,若遍历到x,则将bucket[x]进行加一,以某个元素出现的个数,最后遍历bucket将所有元素倒出来即可。
- 时间复杂度:O(n)
- 空间复杂度:O(n)
- 稳定性:不稳定
- 适用范围:非负整数,且最大值不能过大
package Sort;
public class CountSort {
public static void countSort(int[] vec){
if(vec.length < 2)
return;
int maxValue = Integer.MIN_VALUE;
for(int x : vec){
maxValue = Math.max(maxValue, x);
}
int[] bucket = new int[maxValue + 1];
for(int x : vec){
bucket[x]++;
}
int i = 0;
for(int j = 0; j < bucket.length; j++){
while(bucket[j]-- > 0){
vec[i++] = j;
}
}
}
public static void main(String[] args) {
int[] vec = {5,2,0,7,3,8,12};
countSort(vec);
for(int x : vec){
System.out.print(x + " ");
}
}
}
基数排序
- 基本思想:将数组按每一位分别进行排序,从低位遍历到高位。
- 时间复杂度:O(n)
- 空间复杂度:O(n)
- 稳定性:稳定
- 适用范围:非负整数,数字之间量级可以相差很大
package Sort;
public class RadixSort {
public static void radixSort(int[] vec){
if(vec.length < 2)
return;
radixSort(vec, 0, vec.length-1, maxbits(vec));
}
public static int maxbits(int[] vec){
int maxValue = Integer.MIN_VALUE;
for(int x : vec){
maxValue = Math.max(maxValue, x);
}
int bitCnt = 0;
while(maxValue != 0){
bitCnt++;
maxValue /= 10;
}
return bitCnt;
}
public static int getDigit(int x, int d){
return (x / (int)Math.pow(10, d-1)) % 10;
}
public static void radixSort(int[] vec, int l, int r, int digit){
final int radix = 10;
int[] bucket = new int[r - l + 1];
for(int d = 1; d <= digit; d++){
int[] count = new int[radix];
for(int i = l; i <= r; i++){
int j = getDigit(vec[i], d);
count[j]++;
}
for(int i = 1; i < radix; i++){
count[i] = count[i] + count[i-1];
}
for(int i = r; i >= l; i--){
int j = getDigit(vec[i], d);
bucket[count[j] - 1] = vec[i];
count[j]--;
}
for(int i = 0; i < bucket.length; i++){
vec[l+i] = bucket[i];
}
}
}
public static void main(String[] args) {
int[] vec = {5,2,0,7,3,8,12};
radixSort(vec);
for(int x : vec){
System.out.print(x + " ");
}
}
}