桶排序
| 4 | * 桶排序 |
| 5 | */ |
| 6 | public class BucketSort implements IArraySort { |
| 7 | |
| 8 | private static final InsertSort insertSort = new InsertSort(); |
| 9 | |
| 10 | @Override |
| 11 | public int[] sort(int[] sourceArray) throws Exception { |
| 12 | // 对 arr 进行拷贝,不改变参数内容 |
| 13 | int[] arr = Arrays.copyOf(sourceArray, sourceArray.length); |
| 14 | |
| 15 | return bucketSort(arr, 5); |
| 16 | } |
| 17 | |
| 18 | private int[] bucketSort(int[] arr, int bucketSize) throws Exception { |
| 19 | if (arr.length == 0) { |
| 20 | return arr; |
| 21 | } |
| 22 | |
| 23 | int minValue = arr[0]; |
| 24 | int maxValue = arr[0]; |
| 25 | for (int value : arr) { |
| 26 | if (value < minValue) { |
| 27 | minValue = value; |
| 28 | } else if (value > maxValue) { |
| 29 | maxValue = value; |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | int bucketCount = (int) Math.floor((maxValue - minValue) / bucketSize) + 1; |
| 34 | int[][] buckets = new int[bucketCount][0]; |
| 35 | |
| 36 | // 利用映射函数将数据分配到各个桶中 |
| 37 | for (int i = 0; i < arr.length; i++) { |
| 38 | int index = (int) Math.floor((arr[i] - minValue) / bucketSize); |
| 39 | buckets[index] = arrAppend(buckets[index], arr[i]); |
| 40 | } |
| 41 | |
| 42 | int arrIndex = 0; |
| 43 | for (int[] bucket : buckets) { |
| 44 | if (bucket.length <= 0) { |
| 45 | continue; |
| 46 | } |
| 47 | // 对每个桶进行排序,这里使用了插入排序 |
| 48 | bucket = insertSort.sort(bucket); |
| 49 | for (int value : bucket) { |
| 50 | arr[arrIndex++] = value; |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | return arr; |
| 55 | } |
| 56 | |
| 57 | /** |
| 58 | * 自动扩容,并保存数据 |
| 59 | * |
| 60 | * @param arr |
| 61 | * @param value |
| 62 | */ |
| 63 | private int[] arrAppend(int[] arr, int value) { |
nothing calls this directly
no outgoing calls
no test coverage detected