Another question regarding sorting algorithms.
I've noticed that most minHeap implementations are maxHeap with the two inequality signs regarding tree items inversed, which makes sense and seems to work.
Can somebody put into simple words why minHeap takes so much more time than maxHeap?
EDIT: Nope, they take the same, as long as the functions are called the same way technically. And here's a question about something I was never told during the C++ course.
Why is...
Code:
//
// MinHeaps an array, supposed to be worst-case scenario for a HeapSort.
//
void minHeap(int a[], int N)
{
for (int k = N/2; k > 0; k--) {
upHeap(a, k, N);
}
}
void upHeap(int a[], int k, int N)
{
int T = a[k - 1];
while (k <= N/2) {
int j = k + k;
if ((j < N) && (a[j - 1] > a[j])) {
j++;
}
if (T <= a[j - 1]) {
break;
} else {
a[k - 1] = a[j - 1];
k = j;
}
}
a[k - 1] = T;
}
...a gazillion times faster than...
Code:
void minHeap(int a[], int N)
{
for (int k = N/2; k > 0; k--) {
int T = a[k - 1];
while (k <= N/2) {
int j = k + k;
if ((j < N) && (a[j - 1] > a[j])) {
j++;
}
if (T <= a[j - 1]) {
break;
} else {
a[k - 1] = a[j - 1];
k = j;
}
}
a[k - 1] = T;
}
}
And yes, the only difference is that the first time whatever's inside the for loop is a separate function, the second time the function's code is copied into the for loop.