相信其它不少同窗都是以小顶堆来介绍这一章内容,因此我将以大顶堆来介绍这章内容。html
操做 | 说明 |
---|---|
addElement() | 将给定元素添加到该堆中去 |
removeMax() | 删除堆中最大的元素 |
findMax() | 返回一个指向堆中最大元素的引用 |
findMax操做java
findMax操做将返回一个指向该最大堆中最大元素的引用,也就是根结点的引用。因此实现这一操做只需返回储存在根结点的元素便可。node
关键代码:git
在我看来,这个比较的代码是重中之重的。数组
public int compareTo(PrioritizedObject obj) { int result; if (priority > obj.getPriority()) result = 1; else if (priority < obj.getPriority()) result = -1; else if (arrivalOrder > obj.getArrivalOrder()) result = 1; else result = -1; return result; }
public class HeapNode<T> extends BinaryTreeNode<T> { public HeapNode<T> parent;//指向双亲的指针。 public HeapNode(T obj) { super(obj); parent = null; } }
咱们还须要一个可以跟踪该堆最后一片叶子 的指针:数据结构
public HespNode lastNode;函数
排序方法有两个部分构成:添加列表的每一个元素、一次删除一个元素。学习
堆排序的时间复杂度为O(log n).测试
public class test { public static void main(String[] args) { BigArraryHeap<Integer> temp=new BigArraryHeap<Integer>(); int[] list={36,30,18,40,32,45,22,50}; Object[] list2 = new Object[list.length]; //将数组中的元素添加到大顶堆中 for (int i = 0; i < list.length; i++) temp.addElement(list[i]); System.out.println("大顶堆的输出结果为:"+ temp); System.out.println(); for(int n = 0; n < list2.length; n++){ list2[n] = temp.removeMax(); String result = ""; for(int a = 0; a <= n; a++){ result += list2[a] + " "; } System.out.println("第" + (n+1) + "次排序:" + temp + " ~ " + result); } System.out.println(); System.out.print("最后排序结果: "); String result = ""; for(int m = 0; m < list.length; m++){ result += list2[m] + " "; } System.out.println(result); } }
问题1:如何理解这段话,该怎样实现?.net
一般在堆的实现中,咱们会对二叉树的最后一片叶子进行跟踪记录。
问题1解决方案:
就是在对堆进行删除操做的时候须要将根结点与最后一片叶子结点进行交换位置,因此每一次操做都得更新lastNode结点。
问题2解决方案:书上数组对对进行排序是写了一个方法,当想要进行排序的时候直接调用这个方法就OK,而咱们选在在测试类里面直接进行排序,使用最大堆,取出最大堆输出,而后就能够直接输出。
如图:
问题三:在网上搜寻有关于书上的资料室,出现了这么一个尴尬场面:
以后我点进去看了一下:
原来是讲解了有关:栈内存和堆内存。
讲了这么个些东西,来潦草的总结下:
问题1解决方案:
首先咱们得知道咱们必须运用优先级堆,而且每一次添加元素,优先级都加一(从0开始)。
Object operator= +
转化为char
型数据,可是若是直接转,好比这样(char)operator
是会抛出CalssCastException
错误的!//像这样: String a = String.valueOf(ope.pop());//ope.pop()出来的是一个Object型数据。 operator = a.charAt(0);
错题1及缘由:
What type does "compareTo" return? A .int B .String C .boolean D .char错误缘由:comparaTo方法返回的是 -1,0,1
而return "a".comparaTo("b")>0
为false
orture
无
Since a heap is a binary search tree, there is only one correct location for the insertion of a new node, and that is either the next open position from the left at level h or the first position on the left at level h+1 if level h is full. A .True B .Flase错误缘由:堆是一棵彻底二叉树、不是一颗二叉搜索树。本身瞎了眼!!!!
- 内容很详细,把堆介绍的很透彻, - 运用丰富的图片表达思想、好比插入、删除结点的介绍。 - 提出问题有点少。
这一章比起前面相对比较简单,但本身不能松懈.哎,比较难受的是这两天的假期都要贡献给博客了~~~~~o(╥﹏╥)o
代码行数(新增/累积) | 博客量(新增/累积) | 学习时间(新增/累积) | 重要成长 | |
---|---|---|---|---|
目标 | 5000行 | 30篇 | 400小时 | |
第一周 | 260/0 | 1/1 | 05/05 | |
第二周 | 300/560 | 1/2 | 13/18 | |
第三周 | 212/772 | 1/4 | 21/39 | |
第四周 | 330/1112 | 2/7 | 21/60 | |
第五周 | 1321/2433 | 1/8 | 30/90 | |
第六周 | 1024/3457 | 1/9 | 20/110 | |
第七周 | 1024/3457 | 1/9 | 20/130 | |
第八周 | 643/4100 | 2/11 | 30/170 |
1.优先队列
2.堆排序
3.java 各类数据类型之间的转化
4.java中的栈与堆