bin排序问题

时间:2011-02-05 07:00:48

标签: c++ algorithm sorting bin

  //element of chain.     
    struct studentRecord 
            {
           int score;
           string* name;

           int operator !=(studentRecord x) const
              {return (score != x.score);}
        };


    // binsort,  theChain is a single linked list of students and its element is student Record

         void binSort(chain<studentRecord>& theChain, int range)
            {// Sort by score.

               // initialize the bins
               chain<studentRecord> *bin;
               bin = new chain<studentRecord> [range + 1];

               // distribute student records from theChain to bins
               int numberOfElements = theChain.size();
               for (int i = 1; i <= numberOfElements; i++)
               {
                  studentRecord x = theChain.get(0);
                  theChain.erase(0);
                  bin[x.score].insert(0,x);
               }

               // collect elements from bins
               for (int j = range; j >= 0; j--)
                  while (!bin[j].empty())
                  {
                     studentRecord x = bin[j].get(0);
                     bin[j].erase(0);  ////////// here
                     theChain.insert(0,x);
                  }

               delete [] bin;
            }

chain<studentRecord>单一链接列表;在bin排序中,bin是指向bin[arrange +1]的指针,其元素为chain<studentRecord>。代码bin[j].erase(i)delete节点ibin[j].get(i)将获取节点i的元素(即studentRecord)。在代码中,while (!bin[j].empty())用于清空链,但bin [j]不能为空,因为它是一个元素数组,是吗?

感谢。

1 个答案:

答案 0 :(得分:1)

是的,垃圾箱确实可以是空的。 bin empty 和bin existing 之间存在微妙但重要的区别。你是正确的bin是数组的成员,所以存在位于i的bin,对于数组中的任何i。但是,那个垃圾箱不一定要有任何东西;如果输入列表中没有任何元素碰巧落入该区域,它根本就没有任何内容。

如果你在桌子上摆放一排眼镜并开始用水填充其中一些眼镜,那么这个问题有一个很好的物理类比。连续的所有眼镜都存在并且定义明确,但它们并非都必须是空的,特别是如果你开始将它们倾倒出来(正如你在上面的bin分类示例中所做的那样)。