堆排序

堆是一棵完全二叉树,它的每个结点大于或等于它的任意一个孩子。

在Java中可以用一个ArrayList存储堆,则对于位于 i 处的结点,它的左孩子在位置2i+1处,它的右孩子在位置2i+2处,而它的父亲在位置(i-1)/2处。

1.添加一个新结点:

1 Let the last node be the current node;
2 while(the current node is greater than its parent){
3     Swap the current node with its parent;
4     Now the current node is one level up;
5 }

2.删除根结点

1 Move the last node to replace the root;
2 Let the root be the current node;

 

posted @ 2014-10-10 08:37  soul390  阅读(123)  评论(0)    收藏  举报