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


    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("
    ");  
    }
    
    
    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
    
    
    
    


  • 相关阅读:
    题解 P3071 【[USACO13JAN]座位Seating】
    [luogu]P3398 仓鼠找sugar
    快速输入输出
    Luogu P3939 数颜色
    HEOI2016/TJOI2016 排序
    POI2011 DYN-Dynamite
    USACO17JAN Promotion Counting
    AHOI2008 聚会
    Luogu P4907 A换B problem
    网络流24题 骑士共存问题
  • 原文地址:https://www.cnblogs.com/whzhaochao/p/5023471.html
Copyright © 2020-2023  润新知