我写的这算是桶式排序吗?有资格叫桶式排序吗?求问
public class Sort { public static void main(String[] args) { Sort sort= new Sort();
int[] a={9,8,7,7,7,6,5,4,3,2,1};
sort.bucketSort(a,9 );
for(int i=0;i<a.length;i++)
System.out.println(a[i]);
}
//桶式排序
public void bucketSort(int[] a,int max){
int[] buckets=new int[max+1];
for(int i=0;i<a.length;i++)
buckets[a[i]]++;
int j=0;
for(int i=0;i<buckets.length;i++)
if(buckets[i]>0)
{
for(int k=1;k<=buckets[i];k++)
a[j++]=i;
}
}
}
public class Sort { public static void main(String[] args) { Sort sort= new Sort();
int[] a={9,8,7,7,7,6,5,4,3,2,1};
sort.bucketSort(a,9 );
for(int i=0;i<a.length;i++)
System.out.println(a[i]);
}
//桶式排序
public void bucketSort(int[] a,int max){
int[] buckets=new int[max+1];
for(int i=0;i<a.length;i++)
buckets[a[i]]++;
int j=0;
for(int i=0;i<buckets.length;i++)
if(buckets[i]>0)
{
for(int k=1;k<=buckets[i];k++)
a[j++]=i;
}
}
}
// 计算“落入”各桶内的元素在有序序列中的位置
for (int i = 1; i < max; i++) {
buckets[i] = buckets[i] + buckets[i - 1];
} // 将buckets中的元素完全复制到tmp数组中
int tmp[] = Arrays.copyOf(a, a.length());// 根据buckets数组中的信息将待排序列的各元素放入相应位置
for (int k = a.length - 1; k >= 0; k--) {
a[buckets[tmp[k]]] = tmp[k];
}
有两个错误
// 将buckets中的元素完全复制到tmp数组中 应该是将a复制 a.length
a[buckets[tmp[k]]] = tmp[k]; 这句应该是 --buckets[tmp[k]]这个还真是难理解啊,我在纸上比划半天,现在还不是很清楚
// 桶
int[] buckets = new int[max + 1]; // 计算每个元素在桶出现的次数
for (int i = 0; i < data.length; i++)
buckets[data[i]]++; // 计算“落入”各桶内的元素在有序序列中的位置
for (int i = 1; i < buckets.length; i++) {
buckets[i] = buckets[i] + buckets[i - 1];
} // 将buckets中的元素完全复制到tmp数组中
int tmp[] = Arrays.copyOf(data, data.length); // 根据buckets数组中的信息将待排序列的各元素放入相应位置
for (int k = data.length - 1; k >= 0; k--) {
data[--buckets[tmp[k]]] = tmp[k];
}
}
谢了!