/* heap sort主函数 */ void heap_sort(int heap[], int heap_size) { if (heap == NULL || heap_size < 2) { return; } //构建最大堆 build_max_heap(heap, heap_size); int i; for (i = heap_size - 1; i > 0; i--) { /* 把当前堆的最大值(heap[0])交换到末尾 * 相当于取出最大值,堆的规模变小。 * 交换后的堆不是最大堆,但是根的两颗子树都是最大堆 * 满足调用max_heapify的要求。 */ swap_val(heap, heap + i); heap_size--; //保持最大堆 max_heapify(heap, heap_size, 0); } }
/* 此函数把一颗二叉树中以node为根的子树变成最大堆。 * 注意: 使用的前提条件是 node节点的左右子树(如果存在的话)都是最大堆。 * 这个函数是整个算法的关键。 */ void max_heapify(int heap[], int heap_size, int node) { // 这里先不考虑整数溢出的问题 // 先把注意力放在主要的功能上 // 如果数据规模够大,int类型必然会溢出 int l_child = LEFT(node); int r_child = RIGHT(node); int max_value = node; if (l_child < heap_size && heap[l_child] > heap[max_value]) { max_value = l_child; } if (r_child < heap_size && heap[r_child] > heap[max_value]) { max_value = r_child; } if (max_value != node) { swap_val(heap + node, heap + max_value); // 之后还要保证被交换的子节点构成的子树仍然是最大堆 // 如果不是这个节点会继续"下沉"到合适的位置 max_heapify(heap, heap_size, max_value); } }
int main() { int a=1, b=2; printf("a=%d, b=%d\n", a, b); swap_val(&a, &b); printf("a=%d, b=%d\n", a, b); return 0; }