二叉堆的定义
二叉堆是完全二叉树或者是近似完全二叉树。
二叉堆满足二个特性:
1.父结点的键值总是大于或等于(小于或等于)任何一个子节点的键值。
2.每个结点的左子树和右子树都是一个二叉堆(都是最大堆或最小堆)。
当父结点的键值总是大于或等于任何一个子节点的键值时为最大堆。当父结点的键值总是小于或等于任何一个子节点的键值时为最小堆。下图展示一个最小堆:
堆的存储
一般都用数组来表示堆,i结点的父结点下标就为(i – 1) / 2。它的左右子结点下标分别为2 * i + 1和2 * i + 2。如第0个结点左右子结点下标分别为1和2。
堆排序:
堆排序算法的演示。首先,将元素进行重排,以符合堆的条件。图中排序过程之前简单的绘出了堆树的结构。
public class HeapSort
{
public static void main(String[] args)
{
int[] a = {26, 5, 77, 1, 61, 11, 59, 15, 48, 19};
Sort(a);
}
public static void Sort(int[] a)
{
int n = a.length;
int temp = 0;
Display(a, "Before sort : ");
for(int i=n/2; i>0; i--)
Adjust(a, i-1, n);
for(int i=n-2; i>=0; i--)
{
temp = a[i+1];
a[i+1] = a[0];
a[0] = temp;
Adjust(a, 0, i+1);
}
Display(a, "After sort : ");
}
public static void Adjust(int[] a, int i, int n)
{
int j = 0;
int temp = 0;
temp = a[i];
j = 2 * i + 1;
while(j <= n-1)
{
if(j < n-1 && a[j] < a[j+1])
j++;
if(temp >= a[j])
break;
a[(j-1)/2] = a[j];
j = 2 * j + 1;
}
a[(j-1)/2] = temp;
}
public static void Display(int[] a, String str)
{
System.out.println(str);
for(int i=0; i<a.length; i++)
System.out.print(a[i] + " ");
System.out.println();
}
}