Bucket Sort
时间复杂度O(n+k)
最好情况O(n+k)
最坏情况O(n**2)
空间复杂度O(n+k)
Out-place
桶排序和计数排序有点相似,当桶的数量和数组长度一致甚至更多时就是计数排序。
桶排序的思想是,先根据某些特性将数分到几个桶里,这里桶的个数在这里是个超参数,设置的合理可以有效减少排序时间,最好是均匀地将数放在桶里。
如果桶的设置不当就会出现这种问题
Java:设置桶数为5
import java.util.ArrayList;
import java.util.List;
public class BucketSort {
public BucketSort(int[] arr){
List[] buckets = new ArrayList[5];
for (int i = 0; i < buckets.length; i++) {
buckets[i]=new ArrayList<Integer>();
}
for (int i = 0; i < arr.length; i++) {
int index = i/10;
buckets[index].add(arr[i]);
}
int arrIndex = 0;
for (int i = 0; i < buckets.length; i++) {
buckets[i].sort(null);//自带快排
for (int j = 0; j < buckets[i].size(); j++) {
arr[arrIndex++] = (int) buckets[i].get(j);
}
}
}
}
Python:设置桶数为6
def BucketSort(num_list):
#创建桶不能用buckets = [[]]*6,否则后面加值的时候每个内部list都会加一遍
buckets = [[] for i in range(6)]
for i in num_list:
index = i // 10
buckets[index].append(i)
arr_index = 0
for i in buckets:
sorted(i)#自带排序,归并+选择
for j in i:
num_list[arr_index] = j
arr_index += 1
def main():
num_list = [10, 9, 56, 19, 28, 37, 34]
num_list2 = [5, 4, 3, 1, 2]
BucketSort(num_list)
print(num_list)
if __name__ == "__main__":
main()