【发布时间】:2020-05-24 18:09:28
【问题描述】:
我想要做的是使用链表创建一个计数排序,这样我就可以在同一个索引中链接两个相似的元素,然后从左到右复制到原始数组。但是我的Buckets[i] 始终是NULL,即使在插入之后也是如此。所以我得到的数组不会改变。我不知道我做错了什么。
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *next;
} **Buckets;
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}
int findMax(int A[], int n) {
int i, max = A[0];
for (i = 0; i < n; i++) {
if (A[i] > max)
max = A[i];
}
return max;
}
void Insert(struct Node *p, int x) {
while (p != NULL) {
p = p->next;
}
Node *t = t = (struct Node *)malloc(sizeof(struct Node));
t->data = x;
t->next = NULL;
p = t;
}
int Delete(struct Node *Buckets) {
while (Buckets->next != NULL) {
Buckets = Buckets->next;
}
int temp = Buckets->data;
free(Buckets);
return temp;
}
void BucketSort(int A[], int size) {
int max, i, j;
max = findMax(A, size);
Buckets = new Node * [max + 1];
for (i = 0; i < max + 1; i++) {
Buckets[i] = NULL;
}
for (i = 0; i < size; i++) {
Insert(Buckets[A[i]], A[i]); //insertion
}
i = j = 0;
while (i < max + 1) {
while (Buckets[i] != NULL) {
A[j++] = Delete(Buckets[i]); // copy back in array
}
i++;
}
}
int main() {
int arr[] = { 3, 8, 5, 1, 10 };
int size = sizeof(arr) / sizeof(arr[0]); //5
printf("\nBefore : ");
printArray(arr, size);
BucketSort(arr, size);
printf("\nAfter : ");
printArray(arr, size);
return 0;
}
【问题讨论】:
-
欢迎来到 SO!这被标记为 C,但对我来说它看起来像 C++。有理由不使用 STL 和普通的 C++ 语法吗?此外,它感觉就像一个代码转储。您能否将代码最小化并尝试提供minimal reproducible example 或进一步解释您的思考过程?谢谢。
-
当你插入一个新节点时,你遍历列表,然后将新节点分配给本地指针变量
p,这不会更新列表或列表的头部。事实上,一旦您离开Insert,该节点的句柄就会消失。你可能想要一个指向那里的指针,然后分配*p = <new node>。 -
@ggorlen 嘿,谢谢!!感谢您指出,下次我一定会用干净的代码提供更好的问题,问题已经解决。 ^^
标签: c sorting pointers linked-list counting-sort