heapsort in PriorityQueue
来源:互联网 发布:搜狐动态ip软件 编辑:程序博客网 时间:2024/06/13 07:48
先上图:
size = 8
Pi = (Ci+1)/2-1
CLi = 2Pi+1
CRi = CLi+1
备注:Pi为父节点index
Ci为子节点index
CLi为左子节点index
CRi为右子节点index
PriorityQueue中的数据结构为:
Object[] queue ,是一个数组,如上图所示是以个数组实现的完全二叉树
关键代码:
heapify 为将一个无序的数组变为有序
private void heapify() { for (int i = (size >>> 1) - 1; i >= 0; i--) siftDown(i, (E) queue[i]); }private void siftDown(int k, E x) { int half = size >>> 1; while (k < half) { int child = (k << 1) + 1; Object c = queue[child]; int right = child + 1; if (right < size && comparator.compare((E) c, (E) queue[right]) > 0) c = queue[child = right]; if (comparator.compare(x, (E) c) <= 0) break; queue[k] = c; k = child; } queue[k] = x; }
remove的模块为:
E removeAt(int i) { // assert i >= 0 && i < size; modCount++; int s = --size; if (s == i) // removed last element queue[i] = null; else { E moved = (E) queue[s]; queue[s] = null; siftDown(i, moved); if (queue[i] == moved) { siftUp(i, moved); if (queue[i] != moved) return moved; } } return null; }private void siftUp(int k, E x) { while (k > 0) { int parent = (k - 1) >>> 1; Object e = queue[parent]; if (comparator.compare(x, (E) e) >= 0) break; queue[k] = e; k = parent; } queue[k] = x; }
add模块为:
public boolean offer(E e) { if (e == null) throw new NullPointerException(); modCount++; int i = size; if (i >= queue.length) grow(i + 1); size = i + 1; if (i == 0) queue[0] = e; else siftUp(i, e); return true; }
阅读全文
0 0
- heapsort in PriorityQueue
- 【leetcode】【Medium】【451. Sort Characters By Frequency】【HashMap】【PriorityQueue】【HeapSort】
- Heapsort
- Heapsort
- HeapSort
- heapsort
- HeapSort
- HeapSort
- HeapSort
- heapsort
- heapsort
- heapsort
- HeapSort
- Heapsort
- HeapSort
- heapSort
- HeapSort
- heapSort
- 关系型数据库和非关系型数据库
- python_range(m)迭代+set()去除重复元素
- 移动端效果之Picker
- GreenDao
- 转载with as、case when、merge into、分析函数over()
- heapsort in PriorityQueue
- mysql开发技巧(一)
- spring data jpa的一个异常
- Grade编译错误 java.util.zip.ZipException: duplicate entry的解决方法
- 【卖家必看干货】4大高效评价请求模板,激活各类买家
- oracle listagg() 去重
- Technical Support
- PHPExcel 导入数据导多个工作区(sheet)
- 字符串格式化