function bucket-sort(array, n) is buckets ← new array of n empty lists for i = 0 to (length(array)-1) do insert array[i] into buckets[msbits(array[i], k)] for i = 0 to n - 1do next-sort(buckets[i]) return the concatenation of buckets[0], ..., buckets[n-1]
privateintindexFor(int a, int min, int step) { return (a - min) / step; }
publicvoidbucketSort(int[] arr) {
intmax= arr[0], min = arr[0]; for (int a : arr) { if (max < a) max = a; if (min > a) min = a; } // 該值也可根據實際情況選擇 intbucketNum= max / 10 - min / 10 + 1; ListbuckList=newArrayList<List<Integer>>(); // create bucket for (inti=1; i <= bucketNum; i++) { buckList.add(newArrayList<Integer>()); } // push into the bucket for (inti=0; i < arr.length; i++) { intindex= indexFor(arr[i], min, 10); ((ArrayList<Integer>) buckList.get(index)).add(arr[i]); } ArrayList<Integer> bucket = null; intindex=0; for (inti=0; i < bucketNum; i++) { bucket = (ArrayList<Integer>) buckList.get(i); insertSort(bucket); for (int k : bucket) { arr[index++] = k; } }
}
// 把桶內元素插入排序 privatevoidinsertSort(List<Integer> bucket) { for (inti=1; i < bucket.size(); i++) { inttemp= bucket.get(i); intj= i - 1; for (; j >= 0 && bucket.get(j) > temp; j--) { bucket.set(j + 1, bucket.get(j)); } bucket.set(j + 1, temp); } }
defis_sort(arr: list) -> bool: for i inrange(len(arr) - 1): if arr[i] > arr[i + 1]: returnFalse else: returnTrue
defbucket_sort(arr: list, is_sub_bucket: bool = False): if is_sort(arr): return
bucket_num: int = max(arr) // 10 + 1ifnot is_sub_bucket else10 buckets: list[list] = [[] for _ inrange(bucket_num)]
for a in arr: i: int = a // 10ifnot is_sub_bucket else a % 10 buckets[i].append(a) arr.clear() for bucket in buckets: bucket_sort(bucket, is_sub_bucket=True) arr += bucket