Search code examples
calgorithmsortingheapsort

Heap Sort giving wrong output


Struggled with the heap sort algorithm, figured it out eventually, but still does not work, and I cannot seem to find the problem, maybe because I have been staring at it for the past 3 hours.. The problem is that it gives wrong input. The program compiles and gives no errors. I used Visual Studio 2013. Input: { 1, 4, 5, 3, 2, 7, 8, 5, 4, 7, 8, 1 } Expected Output: Array sorted.

Output: 1 2 3 5 7 1 4 4 7 8 5 8

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

void change(int *a, int *b){
    int aux;
    aux = *a;
    *a = *b;
    *b = aux;
}
void OrganizeHeap(int *A, int n, int i){
    int left = i * 2 + 1, right = i * 2 + 2;
    int largest = i;
    if (left < n && A[left] >= A[i])
        largest = left;

    if (right < n && A[right] >= A[i])
        largest = right;

    if (largest != i){
        change(&A[i], &A[largest]);
            OrganizeHeap(A, n, largest);
    }
}
void BuildHeap(int *A, int n){
    for (int i = n / 2 - 1; i >= 0; i--)
        OrganizeHeap(A, n, i);
}
void HeapSort(int *A, int n){
    BuildHeap(A, n);
    for (int i = n - 1; i >= 0; i--){
        change(&A[0], &A[i]);
        OrganizeHeap(A, i, 0);
    }
}
int main() {
    int max;
    int A[] = { 1, 4, 5, 3, 2, 7, 8, 5, 4, 7, 8, 1 };
    int n = sizeof(A) / sizeof(int);
    HeapSort(A, n);
    for (int i = 0; i < n; i++)
        printf("%d ", A[i]);
    _getch();
    return 0;
}

Solution

  • There are two problems in your code

        if (right < n && A[right] >= A[i])
              largest = right;
    

    What if A[i] is 5, A[left] is 7 then largest will be set to left. Now what if A[right] is 6.A[right] is greater than A[i] so largest will be set to right.largest should be left and not right because A[left] > A[right] So you can do something like

      if (right < n && A[right] >= A[largest]) //see note below
    

    The second problem has already been removed after the code was edited.

    Note:

    while checking you could just use > then instead of >=