简体   繁体   English

LinkedList上的递归合并排序

[英]Recursive Mergesort on LinkedList

I've been getting headaches trying to implement a recursive mergesort but I keep getting problem after problem. 尝试实现递归mergesort一直让我头疼,但问题不断出现。 Right now, I have a lot of trouble when adding elements which has caused 75% of my problems earlier. 现在,我在添加元素时遇到了很多麻烦,这些问题早些时候引起了我75%的问题。 This is the code of the implementation, the main problem is the merge part: 这是实现的代码,主要问题是合并部分:

 static public void DoMerge(LinkedList <Contacto> L, int left, int mid, int right)
 {
     LinkedList <Contacto> temp = new LinkedList <Contacto>();
   int i, left_end, num_elements, tmp_pos, comp;

   left_end = (mid - 1);
   tmp_pos = left;
   num_elements = (right - left + 1);

   while ((left <= left_end) && (mid <= right))
   {
       comp= L.get(left).get_name().compareTo(L.get(mid).get_name());
       if (comp<=0)
       temp.add(tmp_pos++,L.get(left++));
       else
       temp.add(tmp_pos++,L.get(mid++));
   }

   while (left <= left_end)
    temp.add(tmp_pos++,L.get(left++));

   while (mid <= right)
    temp.add(tmp_pos++,L.get(mid++));

   for (i = 0; i < num_elements; i++)
   {
       L.set(right, temp.get(right));
       right--;
   }

}static public void MergeSort_Recursive(LinkedList <Contacto> L, int left, int right)
{
 int mid; 
if (right > left)
 {
   mid = (right + left) / 2;
   MergeSort_Recursive(L, left, mid);
   MergeSort_Recursive(L, (mid + 1), right);
   DoMerge(L, left, (mid+1), right);
 }
}

The main problem again is the merge part which is constantly troubling me, specially adding the elements to the temporary list. 再次出现的主要问题是合并部分,该部分一直困扰着我,特别是将元素添加到临时列表中。 The compiler throws me an out of bounds exception. 编译器使我超出范围。

The problem is 问题是

LinkedList <Contacto> temp = new LinkedList <Contacto>();

You initialized an empty list. 您初始化了一个空列表。 But, this line: 但是,这一行:

temp.add(tmp_pos++,L.get(left++));

You insert an Object to index tmp_pos which can be larger than the current size of temp (first, size of temp is zero). 您将一个对象插入索引tmp_pos ,该对象可以大于当前的temp大小(首先, temp大小为零)。 (Read more about add. ) (了解有关添加的更多信息

You can fix this by understanding that, for merge sort, temp actually is used as a stack, so this part is not necessary temp.add(tmp_pos++,L.get(left++)); 您可以通过了解以下事实来解决此问题:对于合并排序, temp实际上用作堆栈,因此这部分不是必需的temp.add(tmp_pos++,L.get(left++)); , use temp.add(L.get(left++)); ,使用temp.add(L.get(left++)); instead. 代替。 (Replace other statements in similar manner). (以类似方式替换其他语句)。

And for the last part, just use 最后,只需使用

 for (i = 0; i < num_elements; i++)
 {
       L.set(right, temp.removeLast());
       right--;
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM