This might be a weird question but I'm trying to figure out why the following code works.
It seems as though this code should be used where the heap elements index starts at 1 but it's starting at 0 and the sort is completed correctly.
I say that because the left child is calculated as (element*2) and the right child is (element*2 + 1). This would make the left child for the element with index 0 also have index 0.
#include <iostream>
using namespace std;
void siftDown(int numbers[], int root, int bottom) {
int done, maxChild, temp;
done = 0;
while ((root*2 <= bottom) && (!done)) {
if (root*2 == bottom)
maxChild = root * 2;
else if (numbers[root*2] > numbers[root*2 + 1])
maxChild = root * 2;
else
maxChild = root * 2 + 1;
if (numbers[root] < numbers[maxChild]) {
temp = numbers[root];
numbers[root] = numbers[maxChild];
numbers[maxChild] = temp;
root = maxChild;
} else {
done = 1;
}
}
}
void heapSort(int numbers[], int n) {
int i, temp;
for (i = n/2; i >= 0; i--) {
siftDown(numbers, i, n - 1);
}
for (i = n-1; i >= 1; i--) {
temp = numbers[0];
numbers[0] = numbers [i];
numbers [i] = temp;
siftDown(nu开发者_如何转开发mbers, 0, i-1);
}
}
int main() {
int cases;
int n;
int count;
cin >> cases;
for (int i=0; i < cases; i++) {
cin >> n;
int array[n];
for (int j=0; j < n; j++) {
cin >> array[j];
}
heapSort(array, n);
for (int k=0; k < n; k++) {
cout << array[k];
}
cout << endl;
}
}
For the case when root = 0, there are two sub-cases: numbers[0] > numbers[1], or not. In the first, maxchild is set to 0. The next "if" clause - effectively "numbers[0] < numbers[0]" - necessarily evaluates to false, and so "done" is set to 1 and the loop terminates.
If numbers[1] >= numbers[0], then maxchild is set to 1. The next clause becomes "numbers[0] < numbers[1]" which may be true or may be false if numbers[0] == numbers[1]. If it is false, the loop terminates as before. If it is true, numbers[0] and numbers[1] are swapped - thus the larger number correctly moves to the top of the heap - and root becomes 1, the loop continues and in this case you understand how it works.
I think it's easiest to consider this case as a heap where the root only has one child (and all other nodes have two children as normal).
精彩评论