我正在编写一个使用SSN进行LSD基数排序的程序。该程序将数字解析为3位数,并进行3次传递。每次传递我将数字存储到相应的数组元素桶[];如果有重复,我在该位置创建一个链表,并将重复的一个存储在已经存在的链接列表后面。当我尝试在链表的末尾插入时代码中断。
编辑新的错误消息
class node
{
public:
node(int n, node *p){data=n;next=p;}
int data;
node *next;
};
void genData(int *dta, int n)
{
for(int i=0; i < n; i++)// generate the social security numbers at random
dta[i] = rand()%889 + 111 + 1000*(rand()%889 + 111) + 1000000* (rand()%889 + 111);
}
int radixSort(int *dta, int n, int *out)
{
// the dta array contains the data to be sorted.
// n is the number of data items in the array
// out is the array to put the sorted data
node *bucket[1000]; // declare an array of 1000 linked lists (head pointers)
int count = 0; // use this to count the instructions to graph the big-o
for(int i = 0; i < n; i++)out[i] = dta[i];
for (int pass = 0; pass < 3; pass++)
{
for (int j = 0; j < 1000; j++){
bucket[j] = NULL;
}
delete bucket;
delete[]bucket;
for (int i = 0; i < n; i++){
int index=0;
switch (pass)
{
case 0:
index = out[i] % 1000;
case 1:
index = (out[i]/1000) % 1000;
case 2:
index = out[i] / 1000000;
};
if (bucket[index] = NULL){
bucket[index] = new node(out[i], NULL);
}
else{
node *cur=bucket[index];
while (cur->next!= nullptr){ //****access violation reading location
cur = cur->next;
}
node *ptr = new node(out[i], NULL);
cur->next = ptr;
}
}
int idx = 0;
for (int i = 0; i < 1000; i++){
if (bucket[i] == NULL) continue;
else{
out[idx] = bucket[i]->data;
idx++;
count++;
}
}
}
答案 0 :(得分:0)
您的代码中存在许多问题:
index == out[i] % 1000;
这样的行进行比较,我怀疑这是你想要的。作业使用single = for (int j = 0; j < 1000; j++){bucket[j] = NULL;}
不会检查是否已经有一个指针 - 这会在第一次传递后导致内存泄漏。请注意:每个new
都需要delete
。while (cur!= NULL){cur = cur->next;}
退出while循环一旦cur是nullptr - 这意味着尝试取消引用它2行之后试图取消引用nullptr和一个坏主意。为了得到你的最后一个元素,你可能想要检查的是`while(cur-&gt; next!= nullptr)请注意:如果您的编译器支持nullptr
,那么使用它是一个好主意,即使您可能需要通过适当的标志启用C ++ 11。