使用双链表的C++基数排序

C++ radix sort using doubly-linked list

本文关键字:C++ 基数排序 链表      更新时间:2023-10-16

我正在编写一个程序,使用基数排序对数字列表进行排序,但我一直陷入我认为的无限循环中。我认为这要么是我的主要排序函数,要么是我计数函数。你知道我做错了什么吗?

void radix_sort(DLList& list)
{
  DLList lstRay[10];
  int ct = count(list);
  int zeros = 0;
  int tmp = 0;
  int head = 0;
  for(;ct >= 0; ct--)
  {
      while(!list.isEmpty())
      {
        head = list.deleteHead();
        tmp = head / pow(10, zeros);
        tmp = tmp % 10;
        lstRay[tmp].addToTail(head);
      }
      for(int x = 0; x <=9; x++)
      {
        list.append(lstRay[x]);
      }
      zeros++;   
   }      
}
int count(DLList& list)
{
  int ct = 0;
  int ct2 = 0;
  int tmp = 0;
  while(!list.isEmpty())
  {
      ct = ct2;
      tmp = list.deleteHead();
      while(tmp >= 0)
      {
        tmp = tmp/10;
        ct2++;
      }
      if(ct2 < ct)
      {
        ct2 = ct;
      }
    }
    return ct2;
}

您不会在每次迭代中清除lstRay。这意味着当你再次循环时,每个lstRay都越来越长,所以你的列表呈指数级增长。

然而,我很惊讶它能走到这么远——看起来你的计数函数会清除列表。

无限循环在count()中。temp上的循环永远不会终止,因为temp永远不会低于零。

radix_sort函数也有问题。listRay[tmp]未初始化。