I asked this question in another C++ board, but I didn't really understand what they told me. So I would like to ask in here to see what I can do. I'm reading CLRS, I'm in chapter two in the section about Merge Sort, usually when I get through a chapter I implement the algorithms that are explained. I chose to use C++ because it is a language I'm not really adept at, and because I really want to get good at it. However, I'm having trouble figuring out why my merge sort has bad_alloc error. I assume my recursion is breaking something, or my merge function simply reserves too much memory, but I'm really new at memory management and the only time I saw it I didn't understand how it worked. I should also mention that it works great, up until I have more than three elements in an array.
Here's my .h file:
1 2 3 4 5 6 7 8
#ifndef SORTING_H
#define SORTING_H
#include <vector>
std::vector<int> merge_sort(std::vector<int> array, int pos, int size);
std::vector<int> merge(std::vector<int> array, int init, int mid, int size);
#endif
Anyway this is my code, this is my merge function:
The reason for the crash is that at one point in merge(...) a1_size becomes negative (init > mid). Because merge_sort(...) line 11: pos > size/2
Again merge(...) lines 32/37: i/j will probably be out of bounds.
Further more: Since you pass array by value as a copy and in merge_sort(...) you do not assign the return value, at the end you get an unchanged array.