Java实现基于桶式排序思想和计数排序思想实现的基数排序
计数排序
前提:待排序表中的所有待排序关键字必须互不相同;
思想:计数排序算法针对表中的每个记录,扫描待排序的表一趟,统计表中有多少个记录的关键码比该记录的关键码小,假设针对某一个记录,统计出的计数值为c,则该记录在新的有序表中的存放位置即为c。
性能:空间复杂度:o(n);时间复杂度:o(n^2);
public int[] countSort(int[] array){
int[] tempArray = new int[array.length]; //引入辅助数组
for(int i=0;i<array.length;i++){
int count = 0;
for(int j=0;j<array.length;j++){
if(array[i]>array[j]){
count++;
}
}
tempArray[count] = array[i];
}
return tempArray;
}
桶式排序
桶式排序需要待排序的序列满足以下两个特征:
待排序列所有的值处于一个可枚举的范围之类;
待排序列所在的这个可枚举的范围不应该太大,否则排序开销太大。
排序的具体步骤如下:
(1)对于这个可枚举范围构建一个buckets数组,用于记录“落入”每个桶中元素的个数;
(2)将(1)中得到的buckets数组重新进行计算,按如下公式重新计算:
buckets[i] = buckets[i] +buckets[i-1] (其中1<=i<buckets.length);
public static void bucketSort(int[] data) {
//得到待排序元素中的最大值和最小值
int max=data[0],min=data[0];
for(int i=1;i<data.length;i++){
if(data[i]>max){
max = data[i];
}
if(data[i] < min){
min = data[i];
}
}
// 缓存数组
int[] tmp = new int[data.length];
// buckets用于记录待排序元素的信息
// buckets数组定义了max-min+1个桶
int[] buckets = new int[max-min+1];
// 计算每个元素在序列出现的次数
for (int i = 0; i < data.length; i++) {
buckets[data[i] - min]++;
}
// 计算“落入”各桶内的元素在有序序列中的位置
for (int i = 1; i < max - min; i++) {
buckets[i] = buckets[i] + buckets[i - 1];
}
// 将data中的元素完全复制到tmp数组中
System.arraycopy(data, 0, tmp, 0, data.length);
// 根据buckets数组中的信息将待排序列的各元素放入相应位置
for (int k = data.length - 1; k >= 0; k--) {
data[--buckets[tmp[k] - min]] = tmp[k];
}
}
基于桶式排序思想和计数排序思想实现基数排序:
将待排序元素中的每组关键字依次进行桶分配。
public int[] radixSortBuckets(int[] array, int radix) {
// 找到待排序序列中的最大元素
int max = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
// 确定最大元素的位数maxBits
int maxBits = 0;
while (max > 0) {
max = max/10;
maxBits++;
}
int[] tempArray = new int[array.length]; //用于暂存元素
int[] buckets = new int[radix]; //用于桶式排序
int rate = 1;
// 进行maxBits次分配和收集
for(int i=0; i< maxBits;i++){
// 将array中的元素完全复制到arrayTemp数组中
System.arraycopy(array, 0, tempArray, 0, array.length);
Arrays.fill(buckets, 0); // 重置buckets数组
//分配:计算每个待排序元素的子关键字,并将其次数加到对应的桶中
for(int j=0;j<tempArray.length;j++){
buckets[(tempArray[j]/rate)%radix] ++;
}
// 计算“落入”各桶内的元素在有序序列中的位置
for(int k=1;k<buckets.length;k++){
buckets[k] = buckets[k]+buckets[k-1];
}
// 收集:按子关键字对指定的数据进行排序
for(int m=tempArray.length-1;m>=0;m--){
int subKey = (tempArray[m]/rate)%radix;
array[--buckets[subKey]] = tempArray[m];
}
rate *= radix;
}
return array;
}