Java基础知识强化51:经典排序之桶排序(BucketSort)

1. 首先说明三点:

(1)桶排序是稳定的

(2)桶排序是常见排序里最快的一种,比快排还要快…大多数情况下

(3)桶排序非常快,但是同时也非常耗空间,基本上是最耗空间的一种排序算法

 

2. 桶排序的分析过程:

对无序数组有个要求,就是成员隶属于固定(有限的)的区间,如范围为[0-9],考试分数为1-100等

例如待排数字[6,2,4,1,5,9]

准备10个空桶(桶数是固定区间中最大数,比如这里就是10)

[6 2 4 1 5 9]               待排数组

[0 0 0 0 0 0 0 0 0 0]   空桶

[0 1 2 3 4 5 6 7 8 9]   桶编号(实际不存在)

 

(1)顺序从待排数组中取出数字,首先6被取出,然后把6入6号桶,这个过程类似这样:空桶[ 待排数组[ 0 ] ] = 待排数组[ 0 ]

[6 2 4 1 5 9]             待排数组

[0 0 0 0 0 0 6 0 0 0]   空桶

[0 1 2 3 4 5 6 7 8 9]   桶编号(实际不存在)

 

(2)顺序从待排数组中取出下一个数字,此时2被取出,将其放入2号桶,是几就放几号桶:

[6 2 4 1 5 9]               待排数组

[0 0 2 0 0 0 6 0 0 0]   空桶

[0 1 2 3 4 5 6 7 8 9]   桶编号(实际不存在)

 

(3)4,5,6省略,过程一样,全部入桶后变成下边这样:

[6 2 4 1 5 9]               待排数组

[0 1 2 0 4 5 6 0 0 9]   空桶

[0 1 2 3 4 5 6 7 8 9]   桶编号(实际不存在)

 

0表示空桶,跳过,顺序取出即可:1 2 4 5 6 9

 

 

3. 桶排序代码实现:

 1 /* package whatever; // don't place package name! */
 2 
 3 import java.util.*;
 4 import java.lang.*;
 5 import java.io.*;
 6 
 7 /* Name of the class has to be "Main" only if the class is public. */
 8 class Ideone
 9 {
10     public static void main (String[] args) throws java.lang.Exception
11     {
12         int[] Array = { 99, 65, 24, 47, 50, 88,33, 66, 67, 31, 18 };
13         int[] newArray = bucketSort(Array,99);
14         printArray(newArray);
15     }
16     
17     public static int[] bucketSort(int[] array,int maxNumber) {
18         int[] newArray = new int[maxNumber + 1];
19         
20         for(int i=0; i<array.length; i++) {
21             newArray[array[i]] = array[i];
22             
23         }
24         
25         return newArray;
26     }
27     
28     // 打印功能
29     public static void printArray(int[] arr) {
30         System.out.print("[");
31         for (int x = 0; x < arr.length; x++) {
32            
33            if(arr[x] >0) {
34                    System.out.print(arr[x]+" ");
35            }
36         }
37         System.out.println("]");
38     }
39 }

运行效果,如下:

转载于:https://www.cnblogs.com/hebao0514/p/4832191.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值