45 lines
1.1 KiB
C++
45 lines
1.1 KiB
C++
|
/**
|
|||
|
* File: bucket_sort.cpp
|
|||
|
* Created Time: 2023-03-30
|
|||
|
* Author: krahets (krahets@163.com)
|
|||
|
*/
|
|||
|
|
|||
|
#include "../utils/common.hpp"
|
|||
|
|
|||
|
/* Ͱ<><CDB0><EFBFBD><EFBFBD> */
|
|||
|
void bucketSort(vector<float> &nums) {
|
|||
|
// <20><>ʼ<EFBFBD><CABC> k = n/2 <20><>Ͱ<EFBFBD><CDB0>Ԥ<EFBFBD><D4A4><EFBFBD><EFBFBD>ÿ<EFBFBD><C3BF>Ͱ<EFBFBD><CDB0><EFBFBD><EFBFBD> 2 <20><>Ԫ<EFBFBD><D4AA>
|
|||
|
int k = nums.size() / 2;
|
|||
|
vector<vector<float>> buckets(k);
|
|||
|
// 1. <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ԫ<EFBFBD>ط<EFBFBD><D8B7>䵽<EFBFBD><E4B5BD><EFBFBD><EFBFBD>Ͱ<EFBFBD><CDB0>
|
|||
|
for (float num : nums) {
|
|||
|
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ݷ<EFBFBD>ΧΪ [0, 1)<29><>ʹ<EFBFBD><CAB9> num * k ӳ<>䵽<EFBFBD><E4B5BD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Χ [0, k-1]
|
|||
|
int i = num * k;
|
|||
|
// <20><> num <20><><EFBFBD>ӽ<EFBFBD>Ͱ bucket_idx
|
|||
|
buckets[i].push_back(num);
|
|||
|
}
|
|||
|
// 2. <20>Ը<EFBFBD><D4B8><EFBFBD>Ͱִ<CDB0><D6B4><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
|||
|
for (vector<float> &bucket : buckets) {
|
|||
|
// ʹ<><CAB9><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ҳ<EFBFBD><D2B2><EFBFBD><EFBFBD><EFBFBD>滻<EFBFBD><E6BBBB><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>㷨
|
|||
|
sort(bucket.begin(), bucket.end());
|
|||
|
}
|
|||
|
// 3. <20><><EFBFBD><EFBFBD>Ͱ<EFBFBD>ϲ<EFBFBD><CFB2><EFBFBD><EFBFBD><EFBFBD>
|
|||
|
int i = 0;
|
|||
|
for (vector<float> &bucket : buckets) {
|
|||
|
for (float num : bucket) {
|
|||
|
nums[i++] = num;
|
|||
|
}
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
/* Driver Code */
|
|||
|
int main() {
|
|||
|
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ϊ<EFBFBD><CEAA><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ΧΪ [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 << "Ͱ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ɺ<EFBFBD> nums = ";
|
|||
|
printVector(nums);
|
|||
|
|
|||
|
return 0;
|
|||
|
}
|