数据结构:大堆

#include <iostream>
using namespace std;

class Heap
{
public:
	Heap() :size(0), arr(NULL){}
	void Insert(int a[],int n)
	{
		arr = new int[n];
		for (int i = 0; i < n; i++)
		{
			arr[i] = a[i];
		}
		size = n;

		n = size / 2;
		while (n >= 0)
		{
			SetArr(arr,n);
			n--;
		}
	}
	void Sort()//排序。

{ while (size > 0) { int temp = arr[0]; arr[0] = arr[size - 1]; arr[size - 1] = temp; size--; SetArr(arr, 0); } } void Printf(int n) { for (int i = 0; i < n; i++) { cout << arr[i] << " "; } cout << endl; } private: void SetArr(int a[], int n)//调整。 { int i = n; int j = i * 2 + 1; while (j < size) { if (j + 1 < size && arr[j] < arr[j + 1]) j++; if (arr[i] < arr[j]) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } i = j; j = i * 2 + 1; } } private: int size; int *arr; }; int main() { int a[] = {7,6,54,3,5,6,8,9,3,2,1,3,4,6,5555,3,2213,4}; Heap hp; hp.Insert(a,sizeof(a)/sizeof(int)); hp.Sort(); hp.Printf(sizeof(a)/sizeof(int)); return 0; }


posted on 2017-06-26 13:03  ljbguanli  阅读(183)  评论(0编辑  收藏  举报