我正在尝试为使用一系列链表的Bucketsort编写代码。问题是我不确定如何正确实现链接列表。以下代码首先在int main()中创建一个数组,该数组输入要使用Bucketsort排序的一系列元素。在Bucketsort中,该函数应该创建一个用作存储桶的链接列表数组。将数组的元素插入每个存储桶中,以使用插入排序进行排序,然后将存储桶组合在一起并复制回原始数组中。我为Bucketsort函数编写的代码与其余代码不一致。
#include <iostream>
using namespace std;
struct Node
{
int data;
Node *next;
};
struct Node *insertionsort(struct Node*list) {
int j,v,key;
for (j = 2; j < sizeof B; j++){
key = B[j];
v = j - 1;
while (v > 0 && B[v] < key) {
B[v + 1] = B[v];
v = v - 1;
B[v + 1] = key;
}
}
}
void bucketsort(int* arr){
int n = sizeof arr; //determine size of arr
struct Node** B //create an array of arr pointers
// allocate memory for array of pointers to buckets
b = (struct Node **)malloc(sizeof(struct Node*) * n;
//initialize all linked lists in B to NULL
for (int i = 0; i < n-1; i++){
B[i] = NULL;
}
//insert arr[i] into list B[n*arr[i]]
for (int i = 1; i < n; i++){
Node->data = arr[i];
Node->next = B[i];
B[i] = Node;
}
//sort list B[i] using insertion sort
for (int i = 0; i < n-1; i++){
insertionsort(B[i]);
}
//concatenate all buckets into arr[]
int index = 0;
for (int i = 0; i < sizeof arr; i++){
for (int j = 0; j < sizeof B[i]; j++){
arr[index++] = B[i][j];
}
}
}
int main(){
//establish array and the value to be searched
int len;
// cout << "Enter the size of the array: ";
cin >> len;
int* arr = new int[len];
int arri;
// cout << "Enter the values of the array: ";
for (int i = 0; i <= len; i++) {
cin >> arri;
arr[i] = arri;
}
bucketsort(arr);
for (int i = 0; i <= len; i++) {
cout << arr[i] << ";";
}
return 0;
}