1、堆排序算法描述:
(1)定义
#include <iostream> void printArray(int theArray[], int n) { for(int i = 0; i < n; i++) { std::cout << theArray[i] << " "; } std::cout << std::endl; } void adjustHeap(int theArray[], int n, int start) //从start索引处结点开始调整 { if(start < 0 || start >= n) return; int fatherIndex; int leftIndex; int rightIndex; int tmp; fatherIndex = start; leftIndex = 2 * fatherIndex + 1; //start索引处结点的左孩子的索引 rightIndex = leftIndex + 1; //start索引处结点的右孩子的索引 if(rightIndex < n) //start索引处结点存在右孩子结点. { if(theArray[fatherIndex] < theArray[rightIndex]) //右孩子结点大于start索引处结点 ,交换 { tmp = theArray[fatherIndex]; theArray[fatherIndex] = theArray[rightIndex]; theArray[rightIndex] = tmp; } } if(leftIndex < n) //start索引处结点存在左孩子结点,但不一定存在右孩子结点 { if(theArray[fatherIndex] < theArray[leftIndex]) //右孩子结点大于左孩子结点树,交换 { tmp = theArray[fatherIndex]; theArray[fatherIndex] = theArray[leftIndex]; theArray[leftIndex] = tmp; } } adjustHeap(theArray, n, start-1); //再次递归调整start索引处的上一个结点 } void constructHeap(int theArray[], int n) { int start = n / 2; adjustHeap(theArray, n, start); //从length/2处开始调整 } void heapSort(int theArray[], int n) { if(n == 1) //当未排序序列中只剩一个元素时,直接跳出递归 return; int length = n; //printArray(theArray, length); //打印出每次建立最大堆之后,数组排列情况 //将最大堆的堆顶元素与堆末尾元素交换,并取出该元素作为已排序数组元素 int tmp = theArray[0]; theArray[0] = theArray[length-1]; theArray[length-1] = tmp; //再次调整交换后的堆,使得为满足最大堆 --length; //未排序序列长度减一 int start = length / 2; adjustHeap(theArray, length, start); heapSort(theArray, length); //递归进行堆排序 } int main(int argc, char *argv[]) { int myArray[] = {5,90,28,4,88,58,38,18,19,20}; int length = sizeof(myArray) / sizeof(myArray[0]); constructHeap(myArray, length); heapSort(myArray, length); printArray(myArray, length); return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/vgxpm/article/details/47006065