MarkXLII - 10 months ago 44

C++ Question

I'm trying to get the following code for merge sort work with vectors instead of C style arrays and I'm having a hard time figuring out why it crashes with segmentation fault. Can someone help me out in understanding the problem here?

`#include <bits/stdc++.h>`

using namespace std;

void merge(vector<int>& a, int l, int m, int r) {

vector<int> L;

vector<int> R;

for (int i = 0; i <= m; i++)

L.push_back(a[i]);

for (int i = m+1; i <= r; i++)

R.push_back(a[i]);

int i = 0, j = 0; // Initial index of first and second subarray

int k = l; // Initial index of merged subarray

while (i < L.size() && j < R.size()) {

if (L[i] <= R[j]) {

a[k] = L[i];

i++;

}

else {

a[k] = R[j];

j++;

}

k++;

}

// Filling leftovers

while (i < L.size()) {

a[k] = L[i];

k++;

i++;

}

while (j < R.size()) {

a[k] = R[j];

k++;

j++;

}

}

void merge_sort(vector<int>& a, int l, int r) {

if (l < r) {

int m = l + (r-l) / 2; // Avoids integer overflow.

merge_sort(a, l, m);

merge_sort(a, m+1, r);

merge(a, l, m, r);

}

}

int main()

{

vector<int> a = {2, 4, 1, 5, 3, 9};

int size = a.size();

merge_sort(a, 0, size-1);

for (int i = 0; i < size; i++)

cout << a[i] << ' ';

cout << endl;

return 0;

}

Answer Source

You need to go from `l`

to `m`

when filling vector `L`

:

```
void merge(vector<int>& a, int l, int m, int r) {
vector<int> L;
vector<int> R;
for (int i = l; i <= m; i++)
L.push_back(a[i]);
...
}
```

Otherwise `L`

contains additional elements outside the range of interest. Then, index `k`

steps off the end of vector `a`

when iterating for the size of `L`

.