`
leonzhx
  • 浏览: 796798 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Priority Queues

 
阅读更多

1. For collections, which item to delete ?

    Stack: Remove the item most recently added.
    Queue: Remove the item least recently added.
    Randomized queue: Remove a random item.
    Priority queue: Remove the largest (or smallest) item.

 

2. Priority Queue interfaces:

    MaxPQ(): create an empty priority queue
    MaxPQ(Key[] a): create a priority queue with given keys
    void insert(Key v): insert a key into the priority queue
    Key delMax(): return and remove the largest key
    boolean isEmpty(): is the priority queue empty?
    Key max(): return the largest key
    int size(): number of entries in the priority queue

 

3. Find the largest M items in a stream of N items:

 
implementation time space
sort N log N N
elementary PQ M N M
binary heap NlogM M
best in theory N M

 

4. unordered array implementation:

 

public class UnorderedMaxPQ<Key extends Comparable<Key>>
{
    private Key[] pq; // pq[i] = ith element on pq
    private int N; // number of elements on pq
    public UnorderedMaxPQ(int capacity)
    { pq = (Key[]) new Comparable[capacity]; }
    
    public boolean isEmpty()
    { return N == 0; }

    public void insert(Key x)
    { pq[N++] = x; }

    public Key delMax()
    {
        int max = 0;
        for (int i = 1; i < N; i++)
          if (less(max, i)) max = i;
        exch(max, N-1);
        Key result = pq[--N];
        pq[N] = null;
        return result;
    }
}

 

 

5. order of growth of running time for priority queue with N items:

implementation insert del max max
unordered array 1 N N
ordered array N 1 1
goal logN logN logN

 

6. Binary tree: Empty or node with links to left and right binary trees.
    Complete tree: Perfectly balanced, except for bottom level.

    Property: Height of complete tree with N nodes is ⎣log N⎦.



 

7. Binary heap: Array representation of a heap-ordered complete binary tree.
    Heap-ordered binary tree:
    a)  Keys in nodes.
    b)  Parent's key no smaller than children's keys.
    Array representation:
    a)  Indices start at 1.
    b)  Take nodes in level order.

    c)  No explicit links needed!



 

8. Can use array indices to move through binary tree:

    a)  Largest key is a[1], which is root of binary tree.

    b)  Parent of node at k is at k/2.
    c)  Children of node at k are at 2k and 2k+1.

 

9. To eliminate the violation that child's key becomes larger key than its parent's key:

    a)  Exchange key in child with key in parent.

    b)  Repeat until heap order restored.

 

private void swim(int k)
{
    while (k > 1 && less(k/2, k))
    {
      exch(k, k/2);
      k = k/2;
    }
}

 


 

 

10.  Insertion in a heap: Add node at end, then swim it up:

 

public void insert(Key x)
{
  pq[++N] = x;
  swim(N);
}

 Cost : At most 1 + lg N compares.
 

 

11. To eleminate the violation that parent's key becomes smaller than one (or both) of its children's:

    a)  Exchange key in parent with key in larger child.
    b)  Repeat until heap order restored.

 

private void sink(int k)
{
  while (2*k <= N)
  {
    int j = 2*k;
    if (j < N && less(j, j+1)) j++;
    if (!less(k, j)) break;
    exch(k, j);
    k = j;
  }
}

 

 

 

12. Delete the maximum in a heap: Exchange root with node at end, then sink it down:

 

public Key delMax()
{
  Key max = pq[1];
  exch(1, N--);
  sink(1);
  pq[N+1] = null;
  return max;
}

 Cost: At most 2 lg N compares.

 

 

13. Order-of-growth of running time for priority queue with N items:

implementation insert del max max
unordered array 1 N N
ordered array N 1 1
binary heap log N log N 1
d-ary heap logd N d logd N 1
Fibonacci 1 log N 1
impossibl 1 1 1

 

14. Binary heap considerations:

      Immutability of keys:
      a)  Assumption: client does not change keys while they're on the PQ.
      b)  Best practice: use immutable keys.

      Underflow and overflow:
      a)  Underflow: throw exception if deleting from empty PQ.
      b)  Overflow: add no-arg constructor and use resizing array.

 

15. Immutable: String, Integer, Double, Color.
      Mutable: StringBuilder, Stack, Java array.

 

16. Advantages of immutable type:
    a)  Simplifies debugging.
    b)  Safer in presence of hostile code.
    c)  Simplifies concurrent programming.
    d)  Safe to use as key in priority queue or symbol table.
    Disadvantage: Must create new object for each data type value.

 

17. Basic plan for in-place heap sort.
    a)  Create max-heap with all N keys.
    b)  Repeatedly remove the maximum key.

 

18. Heap construction: Build heap using bottom-up method.

   

for (int k = N/2; k >= 1; k--)
  sink(a, k, N);

 

 

19. Java implementation of heap sort :

public class Heap
{
  public static void sort(Comparable[] a)
  {
    int N = a.length;
    for (int k = N/2; k >= 1; k--)
      sink(a, k, N);
    while (N > 1)
    {
      exch(a, 1, N);
      sink(a, 1, --N);
    }
  }

  private static void sink(Comparable[] a, int k, int N)
  { /* as before */ }

  private static boolean less(Comparable[] a, int i, int j)
  { /* as before but convert from 1-based indexing to 0-base indexing*/ }

  private static void exch(Comparable[] a, int i, int j)
  { /* as before but convert from 1-based indexing to 0-base indexing*/ }
}

 

20. Heap construction uses ≤ 2 N compares and exchanges.

      Heapsort uses ≤ 2 N log N compares and exchanges.

      Heapsort is optimal for both time and space, but:
      a)  Inner loop longer than quicksort’s.
      b)  Makes poor use of cache memory. (last item will exchange with first item)
      c)  Not stable.

 

21. Sorting Algorithm Summary:



 

 

  • 大小: 14.5 KB
  • 大小: 25.4 KB
  • 大小: 24.8 KB
  • 大小: 14.7 KB
  • 大小: 43 KB
  • 大小: 66.2 KB
分享到:
评论

相关推荐

    Fast Priority Queues for Cached Memory.

    Fast Priority Queues for Cached Memory.

    PRIORITY QUEUES WITH SIMPLE QUEUE SERVICE

    return Integer.compare(this.priority, other.priority); } public String getMessage() { return message; } } public static void main(String[] args) { // 创建一个包含自定义比较逻辑的优先级队列...

    Java Methods-Heaps and Priority Queues.ppt

    二、优先队列(Priority Queue) 优先队列是一种数据结构,它能够根据优先级来存储和提取数据。优先队列的实现方式有很多种,常见的有基于数组的实现和基于链表的实现。优先队列的操作有add、remove和peek三个基本...

    Group6_Thread_safe_PriorityQueues:LockFreeQueue和PipelinedBlockingQueue的实现

    线程安全PriorityQueues #操作说明实现在并发访问下性能比Java的PriorityBlockingQueue更好的pipelinedPriorityQueue和lockfreePriorityQueue。 #要求Java 1.8+ Eclipse中的Maven插件蚀#如何使用用Eclipse打开...

    高级数据结构PPT 英文版

    Priority queues and merging (Section 5.6) Leftist trees, Binomial heaps and Fibonacci heaps (Sections 9.2, 9.3, and 9.4) Pairing heaps (Section 9.5) Double ended priority queues (Sections 9.6 and ...

    C和C++参考手册chm版

    C/C++ Reference General C/C++ Pre-processor commands Operator Precedence ...C++ Priority Queues C++ Queues C++ Stacks C++ Sets C++ Multisets C++ Maps C++ Multimaps C++ Bitsets All C++ Functions

    非常好用的C和C++函数库电子手册

    包括: General C/C++ Pre-processor commands ...C++ Priority Queues C++ Queues C++ Stacks C++ Sets C++ Multisets C++ Maps C++ Multimaps C++ Bitsets Iterators All C++ Functions 非常好用!英文版的

    C/C++语言参考(英文版)

    C++ 语言参考 英文版 C/C++ Reference General C/C++ ...C++ Priority Queues C++ Queues C++ Stacks C++ Sets C++ Multisets C++ Maps C++ Multimaps C++ Bitsets All C++ Functions

    c / c++ / cpp / stl 中文帮助文档手册chm格式下载

    c / c++ / cpp / stl 中文帮助文档手册chm格式下载 C/C++ 语言参考 ...C++ Priority Queues C++ Queues C++ Sets C++ Stacks C++ Vectors Iterators 全部的 C 函数 全部的 C++ 函数

    C_C++语言参考.

    C/C++ 语言参考 基本C/C++ ...C++ Priority Queues C++ Queues C++ Sets C++ Stacks C++ Vectors Iterators 全部的 C 函数 全部的 C++ 函数 有任何问题请联系 整理者 最后整理于 2/26/2006, 感

    C/C++函数手册-中文版和英文版

    有一份中文版的,一份英文版的。 C++ Information Documentation Reference ...C++ Priority Queues C++ Queues C++ Sets C++ Stacks C++ Vectors Iterators 全部的 C 函数 全部的 C++ 函数

    STL标准模板库简介

    C++_STL标准模板库 比较全面 STL 简介 ...4.4 C++ PRIORITY QUEUES(优先队列) 5 迭代器 5.1 解释 5.2 功能特点 6 C++标准库总结 6.1 容器 6.2 算法 6.3 函数对象 6.4 迭代器 6.5 分配器 6.6 数值

    Python数据结构与算法 英文版

    11.Heaps and Priority Queues 12.Sets, Multisets, and Partitions 13.Garbage Collection and the Other Kind of Heap 14.Algorithmic Patterns and Problem Solvers 15.Sorting Algorithms and Sorters 16.Graphs...

    C++完全帮助文档(手册)

    C++ Priority Queues * C++ Queues * C++ Stacks * C++ Sets * C++ Multisets * C++ Maps * C++ Multimaps * C++ Bitsets * Iterators * Function objects/adapters * General utilities

    C语言参考手册 免积分下载

    Date Standard C Memory Other st andard C functions C++ 标准模板库 C++ Bitsets C++ Double-Ended Queues C++ Lists C++ Maps C++ Multimaps C++ Multisets C++ Priority Queues C++ Queues C++ Sets C++ Stacks ...

    C语言参考手册 C标准 (内含6个chm格式手册)

    Date Standard C Memory Other st andard C functions C++ 标准模板库 C++ Bitsets C++ Double-Ended Queues C++ Lists C++ Maps C++ Multimaps C++ Multisets C++ Priority Queues C++ Queues C++ Sets C++ Stacks ...

    c语言参考手册.rar(内含3个chm格式手册)

    资源描述:(放心中文版的) ---------------------- c参考手册.rar(压缩包) ...C++ Priority Queues C++ Queues C++ Sets C++ Stacks C++ Vectors Iterators 新手、老手都不可错过的好东西!!

    PHP 7 - Data Structures and Algorithms

    Implement linked lists, double linked lists, stack, queues, and priority queues using PHP ? Work with sorting, searching, and recursive algorithms ? Make use of greedy, dynamic, and pattern matching ...

    C 和 C++ 的函数手册.chm

    C++ Priority Queues C++ Queues C++ Sets C++ Stacks C++ Vectors Iterators 《C语言函数大全(语法着色版).chm》内容介绍: C语言函数大全,已包含绝大部分的函数。每个函数包含函数名,功能,用法,举例,...

    C语言库函数查询手册.chm

    资源描述:(放心中文版的) ---------------------- c参考手册.rar(压缩包) ...C++ Priority Queues C++ Queues C++ Sets C++ Stacks C++ Vectors Iterators 等等 这是对于新手、老手都不可错过的好东西!!

Global site tag (gtag.js) - Google Analytics