Próbowałem sobie zrobić sortowanie przez kopcowanie tak jak jest w Cormenie. Kod:
void Sort::heapify(int i, int n)
{
int l, r, largest;
l = 2*i;
r = 2*i + 1;
if ((l <= n) && (tab[l] > tab[i]))
largest = l;
else
largest = i;
if ((r <= n) && (tab[r] > tab[largest]))
largest = r;
if (largest != i)
{
swap(tab[i], tab[largest]);
heapify(largest, n);
}
}
void Sort::heapSort()
{
for (int i = N/2; i >= 0; i--)
heapify(i, N);
int n = N;
for (int i = N-1; i >= 1; i--)
{
swap(tab[0], tab[i]);
n--;
heapify(0, n);
}
}
Jednak algorytm nie sortuje tablicy. Co jest źle? N to stała z rozmiarem tablicy.