using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LeetCode
{
public class Heap
{
void Swap(int[] arr,int i,int j)
{
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
public void Heapify(int[] tree,int n,int i)
{
if (i > n) { return; }
int c1=2*i + 1;
int c2=2*i + 2;
int max = i;
if (c1 < n&&tree[c1] > tree[max])
{
max = c1;
}
if (c2<n&& tree[c2] > tree[max])
{
max = c2;
}
if (max != i)
{
Swap(tree, i, max);
Heapify(tree, n, max);
}
}
public void Build_Heap(int[] tree,int n)
{
int lastNode = n - 1;
int parent = (lastNode - 1) / 2;
for(int i = parent; i >= 0; i--)
{
Heapify(tree, n, i);
}
}
public void Heap_Sort(int[]tree,int n)
{
Build_Heap(tree, n);
for(int i = n - 1; i >= 0; i--)
{
Swap(tree, i, 0);
Heapify(tree, i, 0);
}
}
}
}
堆排序不是稳定排序
时间复杂度:O(nlogn)