1 / 8

Chapter 6: Priority Queues

Mark Allen Weiss: Data Structures and Algorithm Analysis in Java. Chapter 6: Priority Queues. The Selection Problem. Lydia Sinapova, Simpson College. The Selection Problem. Given a list of N elements and an integer k , k  N, find the k-th largest element . Solution 1.

mahsa
Download Presentation

Chapter 6: Priority Queues

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Mark Allen Weiss: Data Structures and Algorithm Analysis in Java Chapter 6: Priority Queues The Selection Problem Lydia Sinapova, Simpson College

  2. The Selection Problem Given a list of N elements and an integer k, k  N, find the k-th largest element.

  3. Solution 1 • Sort the elements in an array • Return the element in the k-th position Complexity: • simple sorting algorithm O(N2) • advanced sorting algorithm O(NlogN)

  4. Solution 2 • Read k elements in an array, sort them • Let Sk be the smallest element • For each next element E do the following: • If E > Sk • remove Sk • insert E in the appropriate position in the array • Return Sk

  5. Solution 2 (cont.) • Complexity:O(N*k) • k2for the initial sorting of k elements • (N-k)*kfor inserting each next element O(k2 )+ O((N-k)*k) = O(k2 + N*k - k2 ) =O(N*k) • Worst case:k =N/2, complexity:O(N2)

  6. Solution 3 Assume we change the heap-order property - the highest priority corresponds to the highest key value. • Read N elements in an array • Build a heap of these N elements - O(N) • Perform kDeleteMaxoperations - O(klogN) Complexity: O(N) + O(k*logN) For k = N/2 the complexity is O(N*logN)

  7. Solution 4 We return back to the usual heap-order property. • Build a heap of k elements. Complexity O(k) • The k-th largest element among k elements is the smallest element in that heap and it will be at the top. • Compare each next element with the top element O(1) • If the new element is larger, DeleteMin the top element and insert the new element in the heap. - O(log(k))

  8. Solution 4 (cont.) At the end of the input the smallest element in the heap is the k-th largest element in the list of N elements. Complexity: O(k) + O((N-k) * log(k)) = O(N*log(k))

More Related