简体   繁体   中英

Recursive Mergesort on LinkedList

I've been getting headaches trying to implement a recursive mergesort but I keep getting problem after problem. Right now, I have a lot of trouble when adding elements which has caused 75% of my problems earlier. 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). (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++)); , use 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--;
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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