Add bucket_sort.cpp and bucket_sort.py (#446)

This commit is contained in:
Yudong Jin 2023-03-30 03:44:26 +08:00 committed by GitHub
parent 475ba8baa7
commit 830ec69d39
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 78 additions and 1 deletions

View file

@ -0,0 +1,44 @@
/**
* File: bucket_sort.cpp
* Created Time: 2023-03-30
* Author: Krahets (krahets@163.com)
*/
#include "../include/include.hpp"
/* 桶排序 */
void bucketSort(vector<float> &nums) {
// 初始化 k = n/2 个桶,预期向每个桶分配 2 个元素
int k = nums.size() / 2;
vector<vector<float>> buckets(k);
// 1. 将数组元素分配到各个桶中
for (float num : nums) {
// 输入数据范围 [0, 1),使用 num * k 映射到索引范围 [0, k-1]
int i = num * k;
// 将 num 添加进桶 bucket_idx
buckets[i].push_back(num);
}
// 2. 对各个桶执行排序
for (vector<float> &bucket : buckets) {
// 使用内置排序函数,也可以替换成其它排序算法
sort(bucket.begin(), bucket.end());
}
// 3. 遍历桶合并结果
int i = 0;
for (vector<float> &bucket : buckets) {
for (float num : bucket) {
nums[i++] = num;
}
}
}
/* Driver Code */
int main() {
// 设输入数据为浮点数,范围为 [0, 1)
vector<float> nums = {0.49f, 0.96f, 0.82f, 0.09f, 0.57f, 0.43f, 0.91f, 0.75f, 0.15f, 0.37f};
bucketSort(nums);
cout << "桶排序完成后 nums = ";
PrintUtil::printVector(nums);
return 0;
}

View file

@ -0,0 +1,33 @@
"""
File: bucket_sort.py
Created Time: 2023-03-30
Author: Krahets (krahets@163.com)
"""
def bucket_sort(nums: list[float]) -> None:
# 初始化 k = n/2 个桶,预期向每个桶分配 2 个元素
k = len(nums) // 2
buckets = [[] for _ in range(k)]
# 1. 将数组元素分配到各个桶中
for num in nums:
# 输入数据范围 [0, 1),使用 num * k 映射到索引范围 [0, k-1]
i = int(num * k)
# 将 num 添加进桶 i
buckets[i].append(num)
# 2. 对各个桶执行排序5
for bucket in buckets:
# 使用内置排序函数,也可以替换成其它排序算法
bucket.sort()
# 3. 遍历桶合并结果
i = 0
for bucket in buckets:
for num in bucket:
nums[i] = num
i += 1
if __name__ == '__main__':
# 设输入数据为浮点数,范围为 [0, 1)
nums = [0.49, 0.96, 0.82, 0.09, 0.57, 0.43, 0.91, 0.75, 0.15, 0.37]
bucket_sort(nums)
print("桶排序完成后 nums =", nums)

View file

@ -74,7 +74,7 @@
[class]{}-[func]{bucketSort}
```
!!! question "桶排序的应用场景是什么?"
!!! question "桶排序的应用场景是什么?"
桶排序一般用于排序超大体量的数据。例如输入数据包含 100 万个元素,由于空间有限,系统无法一次性将所有数据加载进内存,那么可以先将数据划分到 1000 个桶里,再依次排序每个桶,最终合并结果即可。