算法介绍
下面定义出自wikipediahttps://zh.wikipedia.org/wiki/%E6%A1%B6%E6%8E%92%E5%BA%8F
桶排序(Bucket sort)或所谓的箱排序,是一个排序算法,工作的原理是将数组分到有限数量的桶里。每个桶再个别排序(有可能再使用别的排序算法或是以递归方式继续使用桶排序进行排序)。桶排序是鸽巢排序的一种归纳结果。当要被排序的数组内的数值是均匀分配的时候,桶排序使用线性时间(Θ(n))。但桶排序并不是比较排序,他不受到O(n log n)下限的影响。
桶排序以下列程序进行:
- 设置一个定量的数组当作空桶子。
- 寻访序列,并且把项目一个一个放到对应的桶子去。
- 对每个不是空的桶子进行排序。
- 从不是空的桶子里把项目再放回原来的序列中。
一个例子
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
|
public class SortAlgoBucketSort {
public static int[] bucketSort(int[] arr){ int bucketNum = 10; Integer[][] buckets = new Integer[bucketNum][arr.length]; for (int num : arr){ int bucketIdx = num / 10; for (int j = 0; j < arr.length; j++){ if (buckets[bucketIdx][j] == null){ buckets[bucketIdx][j] = num; break; } } }
for (int i = 0; i < buckets.length; i++){ for (int j = 1; j < buckets[i].length; ++j){ if(buckets[i][j] == null){ break; } int value = buckets[i][j]; int position = j; while (position > 0 && buckets[i][position-1] > value){ buckets[i][position] = buckets[i][position-1]; position--; } buckets[i][position] = value; } } int k = 0; for (int i = 0; i < bucketNum; i++){ for (int j = 0; j < buckets[i].length; j++){ if (null == buckets[i][j]){ continue; } arr[k++] = buckets[i][j]; } } return arr; }
private static void printArray(int[] arr){ for (int num : arr){ System.out.printf("%d,", num); } } public static void main(String[] args) { int[] arr = new int[]{3,1,41,62,73,22}; arr = bucketSort(arr); printArray(arr); } }
|
更多参考
https://www.byvoid.com/blog/sort-radix