标签:return n个元素 一个 最大堆 while 最大 tor div c++
#include<iostream> #include<vector> #include<stack> #include<algorithm> #include<string> #include<set> #include <functional> using namespace std; //构造最大堆 void MaxHeapFixDown(int a[], int i, int n) { int j = 2 * i + 1; int temp = a[i]; while (j<n) { if (j + 1 < n&&a[j] < a[j + 1]) ++j; if (temp>a[j]) break; else { a[i] = a[j]; i = j; j = 2 * i + 1; } } a[i] = temp; } //堆排序 void HeapSort(int a[], int n) { for (int i = n / 2 - 1; i >= 0; i--) MaxHeapFixDown(a, i, n);//n个元素,最后一个非叶结点下标:n/2-1 for (int i = n - 1; i >= 1; i--) { swap(a[i], a[0]); MaxHeapFixDown(a, 0, i); } } int main() { int a[10] = { 4,8,7,0,3,5,9,1,1,8 }; HeapSort(a, 10); for (int i = 0; i < 10; i++) cout << a[i] << " "; cout << endl; return 0; }
标签:return n个元素 一个 最大堆 while 最大 tor div c++
原文地址:http://www.cnblogs.com/vincent93/p/7552518.html