I am trying to implement the Mergesort algorithm in C++. You can see my implementation below. When I run the algorithm I get the following error:
libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: vector
Abort trap: 6
While this is my first time working in C++, I assume that this error means that I pass in an index that is outside the bounds of some vector. Is this correct?
If this is correct, I cannot figure out where I am exceeding the bounds of some vector. However, I printed a few values to the console and noticed that the program fails to print the elements in the vector right. Maybe this gives a hint for where the index is out of bounds.
Mergesort implementation
#include <iostream>
#include <vector>
void merge(std::vector<int> left, std::vector<int> right, std::vector<int> array)
{
int lengthLeft = left.size();
int lengthRight = right.size();
int i = 0; // index of smallest unpicked element in left
int j = 0; // index of smallest unpicked element in right
int k = 0; // position to be filled in array
while (i < lengthLeft && j < lengthRight)
{
if (left.at(i) <= right.at(j))
{
array.at(k) = left.at(i);
k++;
i++;
}
else
{
array.at(k) = right.at(j);
k++;
j++;
}
}
while (i < lengthLeft)
{
array.at(k) = left.at(i);
k++;
i++;
}
while (j < lengthRight)
{
array.at(k) = right.at(j);
k++;
j++;
}
}
std::vector<int> mergesort(std::vector<int> array)
{
int length = array.size();
std::cout << "Array Size: " << length << '\n';
if (length < 2)
{
return array;
}
int mid = length / 2;
std::cout << "mid = " << mid << '\n';
// Temporary vectors.
std::vector<int> left(mid);
std::vector<int> right(length - mid);
std::cout << "Left size: " << left.size() << '\n';
std::cout << "Right size: " << right.size() << '\n';
// Moving elements into temporary vectors.
for (int i = 0; i <= mid; i++)
{
left.at(i) = array.at(i);
std::cout << "Left at i: " << left.at(i) << '\n';
}
for (int i = mid + 1; i < length; i++)
{
right.at(i) = array.at(i);
std::cout << "Right at i: " << right.at(i) << '\n'; // <-- THIS DOES NOT PRINT
}
mergesort(left);
mergesort(right);
merge(left, right, array);
return array;
}
int main()
{
std::vector<int> vect = {5, 4, 3, 2, 1};
for (int i : vect)
{
std::cout << i << " " << '\n';
}
mergesort(vect);
for (int i : vect)
{
std::cout << i << '\n';
}
return 0;
}
Console output
5
4
3
2
1
Array Size: 5
mid = 2
Left size: 2
Right size: 3
Left at i: 5
Left at i: 4
libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: vector
Abort trap: 6