Siddharth Saurav
Siddharth Saurav

Reputation: 27

Merge-Sort code implementation in C++

I am trying to implement Merge Sort in C++ using vectors and iterators. The program compiles fine but when i try to run it, it crashes. I tried debugging it but with no success.

The implementation using arrays is straight forward but when I try to implement the exact same algorithm using vectors the program fails to run.

#include <iostream>
#include <vector>
#include <algorithm>

void mergesort(std::vector<int>& A, int l, int r);

void merge(std::vector<int>& A, int l, int m, int r);


void mergesort(std::vector<int>& A, int l, int r) {


    if(l < r) {

        int m = l + (r - l) / 2;

        mergesort(A, l, m);

        mergesort(A, m + 1, r);

        merge(A, l, m, r);

    } 
}

void merge(std::vector<int>& A, int l, int m, int r) {

   std::vector<int> L(A.begin() + l, A.begin() + (m - 1));
   std::vector<int> R(A.begin() + m, A.begin() + r);

   std::vector<int>::iterator i = L.begin();
   std::vector<int>::iterator j = R.begin(); 
   std::vector<int>::iterator k = A.begin() + l;

   while(i != L.end() && j != R.end()) {
       if(*i <= *j) {
           *k = *i;
           i++;
       }
       else {
           *k = *j;
           j++;
       }
       k++;
   }

   while(i != L.end()) {
       *k = *i;
       i++;
       k++;
   }

   while(j != R.end()) {
       *k = *j;
       j++;
       k++;
   }
}

void print_vector(std::vector<int> A) {

    std::vector<int>::iterator it;

    for(it = A.begin(); it != A.end(); ++it) {
        std::cout << *it << " "; 
    }
}


int main() {
    std::vector<int> A = {178, 1156, 136, 5, 6, 7};
    mergesort(A, 0, A.size() - 1);

    print_vector(A);
}

Upvotes: 0

Views: 713

Answers (2)

cse
cse

Reputation: 4104

The problem is in memory allocation for vectors L and R in function void merge(std::vector<int>& A, int l, int m, int r).

Following is corrected code snippet, though not optimized(You are free to do optimization ;) ):

std::vector<int> L;
std::vector<int> R;
int n1 = m - l + 1;
int n2 =  r - m;
if(n1 > 0)
{
   for(int i=0; i<n1; i++) L.push_back(0);
   std::copy(A.begin() + l, A.begin() + (l+n1), L.begin());
}
if(n2 > 0)
{
   for(int i=0; i<n2; i++) R.push_back(0);
   std::copy(A.begin() + (l+n1), A.begin() + (l+n1+n2), R.begin());
}

You can find the complete working code here

Upvotes: 0

marom
marom

Reputation: 5230

In this section

if(l < r) {
    int m = l + (r - l) / 2;
    mergesort(A, l, m);
    mergesort(A, m + 1, r);
    merge(A, l, m, r);

} 

When r = l + 1 you get m = l and then you call mergesort asking the function to sort an empty vector, while the code of mergesort assumes that it is not empty.

What is

 std::vector<int> L(A.begin() + l, A.begin() + (m - 1));

in this case?

This should be a good starting point to carry on debugging.

Upvotes: 2

Related Questions