您的位置:首页 > 其它

桶排序(Bucket Sort)----(排序算法七)

2013-10-24 19:34 489 查看

1.算法原理

将元素的值放入另一数组下标与其相等的位置

排序前: 6 2 4 1 5 9

桶中:bucket[10]= 0 1 2 0 4 5 6 0 0 9

有bucket[6]=6,bucket[2]=2,bucket[4]=4,bucket[1]=1,bucket[5]=5,bucket[9]=9

2.代码实现

#include <stdio.h>

//printArray打印出数组
void printArray(int a[],int size){
//   printf("数组为:[%d] ",a[0]);
for (int i=0;i<size;i++)
{
printf(" %x ",a[i]);
}
printf("\n");
}

void main()
{
int  a[6] ={ 6, 2, 4, 1, 5, 9 };
int  len=6;
//分配空桶
int  bucket[10]={0} ;
printf("排序前:");
printArray(a,len);
//直接以每个待排数字为索引,将自己的值赋值给当前桶
for (int i = 0; i < len; i++) {
bucket[a[i]] = a[i];
}
//跳过值为0的空桶,顺序输出即可
int temp=0;
for (int j = 0; j < 10; j++){
if (bucket[j] > 0)
a[temp++]=bucket[j];
}
printf("排序后:");
printArray(a,len);
}


3.排序结果

排序前: 6  2  4  1  5  9
排序后: 1  2  4  5  6  9
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: