krahets 7 months ago
parent b5f94abec9
commit 3dcdda193f

@ -344,24 +344,20 @@ comments: true
int k = n / 2; // 初始化 k = n/2 个桶 int k = n / 2; // 初始化 k = n/2 个桶
int *sizes = malloc(k * sizeof(int)); // 记录每个桶的大小 int *sizes = malloc(k * sizeof(int)); // 记录每个桶的大小
float **buckets = malloc(k * sizeof(float *)); // 动态数组的数组(桶) float **buckets = malloc(k * sizeof(float *)); // 动态数组的数组(桶)
for (int i = 0; i < k; ++i) {
// 为每个桶预分配足够的空间 // 为每个桶预分配足够的空间
for (int i = 0; i < k; ++i) {
buckets[i] = (float *)malloc(n * sizeof(float)); buckets[i] = (float *)malloc(n * sizeof(float));
sizes[i] = 0; sizes[i] = 0;
} }
// 1. 将数组元素分配到各个桶中 // 1. 将数组元素分配到各个桶中
for (int i = 0; i < n; ++i) { for (int i = 0; i < n; ++i) {
int idx = (int)(nums[i] * k); int idx = (int)(nums[i] * k);
buckets[idx][sizes[idx]++] = nums[i]; buckets[idx][sizes[idx]++] = nums[i];
} }
// 2. 对各个桶执行排序 // 2. 对各个桶执行排序
for (int i = 0; i < k; ++i) { for (int i = 0; i < k; ++i) {
qsort(buckets[i], sizes[i], sizeof(float), compare); qsort(buckets[i], sizes[i], sizeof(float), compare);
} }
// 3. 合并排序后的桶 // 3. 合并排序后的桶
int idx = 0; int idx = 0;
for (int i = 0; i < k; ++i) { for (int i = 0; i < k; ++i) {

@ -344,24 +344,20 @@ comments: true
int k = n / 2; // 初始化 k = n/2 個桶 int k = n / 2; // 初始化 k = n/2 個桶
int *sizes = malloc(k * sizeof(int)); // 記錄每個桶的大小 int *sizes = malloc(k * sizeof(int)); // 記錄每個桶的大小
float **buckets = malloc(k * sizeof(float *)); // 動態陣列的陣列(桶) float **buckets = malloc(k * sizeof(float *)); // 動態陣列的陣列(桶)
for (int i = 0; i < k; ++i) {
// 為每個桶預分配足夠的空間 // 為每個桶預分配足夠的空間
for (int i = 0; i < k; ++i) {
buckets[i] = (float *)malloc(n * sizeof(float)); buckets[i] = (float *)malloc(n * sizeof(float));
sizes[i] = 0; sizes[i] = 0;
} }
// 1. 將陣列元素分配到各個桶中 // 1. 將陣列元素分配到各個桶中
for (int i = 0; i < n; ++i) { for (int i = 0; i < n; ++i) {
int idx = (int)(nums[i] * k); int idx = (int)(nums[i] * k);
buckets[idx][sizes[idx]++] = nums[i]; buckets[idx][sizes[idx]++] = nums[i];
} }
// 2. 對各個桶執行排序 // 2. 對各個桶執行排序
for (int i = 0; i < k; ++i) { for (int i = 0; i < k; ++i) {
qsort(buckets[i], sizes[i], sizeof(float), compare); qsort(buckets[i], sizes[i], sizeof(float), compare);
} }
// 3. 合併排序後的桶 // 3. 合併排序後的桶
int idx = 0; int idx = 0;
for (int i = 0; i < k; ++i) { for (int i = 0; i < k; ++i) {

Loading…
Cancel
Save