Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Java 9 Data Structures and Algorithms

You're reading from   Java 9 Data Structures and Algorithms A step-by-step guide to data structures and algorithms

Arrow left icon
Product type Paperback
Published in Apr 2017
Publisher Packt
ISBN-13 9781785889349
Length 340 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Debasish Ray Chawdhuri Debasish Ray Chawdhuri
Author Profile Icon Debasish Ray Chawdhuri
Debasish Ray Chawdhuri
Arrow right icon
View More author details
Toc

Table of Contents (13) Chapters Close

Preface 1. Why Bother? – Basic FREE CHAPTER 2. Cogs and Pulleys – Building Blocks 3. Protocols – Abstract Data Types 4. Detour – Functional Programming 5. Efficient Searching – Binary Search and Sorting 6. Efficient Sorting – quicksort and mergesort 7. Concepts of Tree 8. More About Search – Search Trees and Hash Tables 9. Advanced General Purpose Data Structures 10. Concepts of Graph 11. Reactive Programming Index

Sorting using a priority queue


Since a priority queue always returns the minimum element, if we insert all input elements and then keep dequeuing them, they would be dequeued in sorted order. This can be used to sort a list of elements. In our example, we will add a new method called the LinkedList implementation. This implementation sorts the elements using PriorityQueue. First insert all the elements into the priority queue. Then, dequeue the elements and append them back to the linked list:

public void sort(Comparator<E> comparator){
    PriorityQueue<E> priorityQueue = new LinkedHeap<E>(comparator);

    while (first!=null){
        priorityQueue.enqueue(getFirst());
        removeFirst();
    }

    while (priorityQueue.checkMinimum()!=null){
        appendLast(priorityQueue.dequeueMinimum());
    }
}

Both enqueue and dequeue have θ(lg n) complexity, and we have to enqueue and dequeue each of the elements. We have already seen this: lg 1 + lg 2 + … + lg n = θ(n lg n...

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime