2012-03-13 61 views
0

我的家庭作业有问题,我不知道我在哪里出错了。我必须设计一个用于基数排序的函数,使用bucket和k rounds。我需要保留桶中列表项的顺序,因此我需要为每个桶保留两个点 - 前后。 但是,当我编译我的代码并运行带有10个需要排序的数字的测试代码时,我的输出仅包含3个数字。如果它的20个号码,它只打印2.你能帮我吗?这是我的代码,谢谢你的时间。编辑:由leastSigDig我的意思是有效数字我必须改变,因为它是一个不好的名字基数排序C++作业

#include <cstdlib> // Provides size_t and NULL 
#include <iostream> 
#include <stdio.h> 
#include <stdlib.h> 
#include <math.h> 
using namespace std; 

struct listnode { struct listnode * next; 
        unsigned long  value; } ; 

struct listnode *radixsort (struct listnode *data, int a, int k){ 
    struct listnode *front [a], *rear [a], *cursor; 
    int i=0 , j = 0, leastSigDig,base10num; 
    if (data == NULL) {return data;} 

    for (i;i<k;i++){ 
     base10num= pow(a,i); 
     cursor = data; 
     for (j=0; j<a; j++){ 
      front [j] = NULL; 
      rear [j] = NULL; 
     } 
     while (cursor != NULL){ 
      leastSigDig = ((cursor->value)/base10num)%a; 
      if (rear [leastSigDig]!= NULL){ 
       rear[leastSigDig]->next= cursor; 
       rear [leastSigDig]= cursor; 
      } 
      else if (cursor == NULL) { 
       rear [leastSigDig] = cursor; 
      } 
      cursor = cursor->next; 
     } 

     //Linking 
      cursor = NULL; 
for (int y=0; y< a-1; y++){ 
    int z= y+1; 
    if (front [y] == NULL) 
     continue; 
    else if (cursor == NULL){ 
      cursor = front [y]; 
      rear [y]->next = front [z]; 
     } 
    else if (cursor != NULL) 
      rear [y]->next = front [z]; 


    data = cursor; 
    } 
     } 
    } 
    return data; 
} 


int main(void) 
{ 
    long i, length=10; 
    long a = 10; // working with base 10 
    long k = log10(length*a); 
    struct listnode *node, *space; 
    space = (struct listnode *) malloc(length*sizeof(struct listnode)); 
    for(i=0; i< length; i++) { 
     (space + i)->value = 2*((17*i)%length); 
     (space + i)->next = space + (i+1); 
    } 
    (space+(length-1))->next = NULL; 
    node = space; 
    struct listnode * temp =node; 
    cout<<endl<<"List before radixsort\n" <<endl ; 
    while(temp!=NULL) 
    { 
     cout << temp->value << "\t"; 
     temp = temp->next; 
    } 

    node = radixsort(node,a,k); 

    listnode *check = node; 
    cout << "\n\nList after radixsort \n\n"; 
    while (check) 
    { 
     cout << check->value << "\t"; 
     check = check->next; 
    } 
    cout << "\n\n"; 
    exit(0); 
} 
+0

我已经恢复了您删除的所有代码。请不要从你的问题中删除代码 - 你永远不会得到这样的答案! – razlebe 2012-03-13 13:12:04

+2

唉!我的眼睛!! – 2012-03-13 13:15:37

回答

2

至少有一个问题就在这里:

//Linking 
int y= 0; 

for (int y; y< a-1; y++){ 

for循环变量y阴影在外部范围内的y。这意味着循环内部的y未初始化,您将进入杂草。

你应该调高编译器的警告级别并注意它所说的内容。

+0

我重写了链接部分,但仍然有一个问题 – Ivan 2012-03-13 20:22:35

+0

也改变了其他如果后部[sigDig] == NULL为游标==桶时排序 – Ivan 2012-03-13 20:23:38