堆排序
2013-11-01 14:46
211 查看
二叉堆的定义
二叉堆是完全二叉树或者是近似完全二叉树。二叉堆满足二个特性:
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();
}
}
相关文章推荐
- 冒泡排序,选择排序,快速排序,堆排序与二分查找算法
- 【排序算法】之堆排序的实现
- 第十六周上机实践—项目1(3)—验证算法 堆排序 归并排序 基数排序
- 浅谈算法和数据结构: 五 优先级队列与堆排序
- 第16周SHH数据结构-【项目1-验证算法(6)堆排序 】
- 树和树结构(1) : 二叉堆和堆排序
- 排序算法(二)之希尔排序、堆排序
- 堆排序和优先级队列
- python排序-堆排序
- 排序——堆排序(Heap Sortd)
- 排序算法-堆排序
- 算法导论学习笔记(一)排序算法之堆排序
- (6)排序算法——堆排序
- 排序七部曲之(三)堆排序
- 用仿函数实现大小堆及堆排序
- java实现 堆排序
- 堆排序改进
- 排序问题-堆排序
- 七、堆排序
- [028]八大排序算法详解——堆排序