简体   繁体   中英

How to write merge function for mergeSort in C++?

I'm learning C++ and trying to write the merge function that will take two sorted lists and combine them into one sorted list. This should run in O(n) time. Below is my code:

LinkedList<T> LinkedList<T>::merge(const LinkedList<T>& other) const {

  LinkedList<T> left = *this;
  LinkedList<T> right = other;

  LinkedList<T> merged;

  if (left.size() <= 1) {
    return left;
  }
  else{
    while (left.size() > 0 && right.size() > 0){

          if (left.front() <= right.front()){
            merged.pushBack(left.front());
            left.popFront();
          }
          else {
            merged.pushBack(right.front());
            right.popFront();
          }
      }
  }

  return merged;
}

This is my test:

Testing merge():
Left List: [(1)(3)(5)]  Right List: [(-1)(2)(10)(20)]
Merged: [(-1)(1)(2)(3)(5)]
Expected: [(-1)(1)(2)(3)(5)(10)(20)]

I think this is happening because when one of the lists become empty, the loop stops. Can anyone suggest me on how to deal with this? Many thanks.

After the main while loop where it has the condition to run until both arrays contain elements. So when one of them is empty it exits and one of the arrays might still contain the left-over elements. You need to add a while loop outside also to go thru remaining elements add to the result array. Here is the sample:

while (left.size() > 0)
{
            merged.pushBack(left.front());
            left.popFront();
}
while (right.size() > 0)
{
            merged.pushBack(right.front());
            right.popFront();
}

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