Skip to content

Fixed heap_sort_c++#1060

Open
yamanalrfai wants to merge 1 commit intomatthewsamuel95:masterfrom
yamanalrfai:fix_heap_sort_c++
Open

Fixed heap_sort_c++#1060
yamanalrfai wants to merge 1 commit intomatthewsamuel95:masterfrom
yamanalrfai:fix_heap_sort_c++

Conversation

@yamanalrfai
Copy link
Copy Markdown

@yamanalrfai yamanalrfai commented Apr 5, 2026

there some logical bugs in C++ code for the heap_sort

in a C++ version of heap_sort there are 3 wrongs

  1. the function minheapify (line: 49)
    if (l >= limit || r >= limit)
    return;
    using || is not right because if the r >= limit then it never check the left node.
    so we must cheek like this:
void minheapify(int i, int limit) {
  int l = left(i);
  int r = right(i);
  int smallest = i;
  if (l < limit && harr[l] < harr[i])
    smallest = l;
  if (r < limit && harr[r] < harr[smallest])
    smallest = r;
  if (i != smallest) {
    swap( & harr[i], & harr[smallest]);
    minheapify(smallest, limit);
  }
}
  1. the function sort() (line: 64)
    for (i = 1; i < heap_size - 1; i++) {
    it must be
    for (i = 1; i < heap_size; i++) {

  2. need to add buildHeap before start the sort so it become

void buildHeap() {
  for (int i = (heap_size / 2) - 1; i >= 0; i--) {
    minheapify(i, heap_size);
  }
}

void sort() {
  buildHeap(); 
  int i;
  for (i = 1; i < heap_size; i++) {
    swap( & harr[0], & harr[heap_size - i]);
    minheapify(0, heap_size - i);
  }
}

and for Memory leek use Destructor

~heap() {
  delete[] harr;
}

I will not add this Because your class manages a raw memory pointer (harr), if you ever tried to copy this heap like this:
heap h2 = h;
...both heaps would point to the exact same array in memory. Modifying one would break the other, and when they are destroyed, the program would try to delete[] the same memory twice, causing a crash.

I will open a PR to add this thing
here it if still you need it after 6 years : https://github.com/matthewsamuel95/ACM-ICPC-Algorithms/pull/1060/changes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant