I am attempting to implement Heap sort in my program to learn more about sorting algorithms. However I am running in to an issue.
I call Heap sort in main like this:
Main:
heap_sort(h_vector);
Where h_vector is a randomly sized vector with random ordered elements. My heap sort algorithm looks like.
Heap Sort:
void max_heapify(std::vector<int>& v, int i)
{
int left = i + 1, right = i + 2;
int largest;
if( left <= v.size() && v[left] > v[i])
{
largest = left;
}
else
{
largest = i;
}
if( right <= v.size() && v[right] > v[largest])
{
largest = right;
}
if( largest != i)
{
std::swap(v[i], v[largest]);
max_heapify(v,largest);
}
}
void build_max_heap(std::vector<int>& v)
{
for( int i = v.size() - 2; i >= 0; --i)
{
max_heapify(v, i);
}
}
void heap_sort(std::vector<int>& v)
{
build_max_heap(v);
int x = 0;
int i = v.size() - 1;
while( i > x)
{
std::swap(v[i],v[x]);
++x;
--i;
}
}
Whenever I add this sort to my program I get the following error.
Error:
*** glibc detected *** ./a.out: free(): invalid next size (normal): 0x096c82d0 ***
I am not sure what could be causing this. I thought at first that my alogrithm might be going out of bounds of the vector but I have checked a few times and I do not see where. Any ideas? Thanks for your help in advance.
At the very first invokation of
max_heapify(), you invoke it withi = v.size() - 2Thus, when you set
right = i + 2;you actually set:right = v.size()Now, look at this:
Note that
right <= v.size(), and you are now trying to accessv[right], which is out of bound.Note that the last index of
visv[v.size() -1]– so all your if statements should beright < v.size()[instead<=]I assume solving these issues will solve your bug eventually.