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

In-place heap sort


We can use an array-based heap implementation to do an in-place sort of the elements of an array. The trick is to use the same array for backing the heap. In the beginning, we simply insert the elements in the heap from the beginning of the array. We achieve this by replacing the array in the heap, except the one that is passed. Since the heap also uses the space from the beginning, it does not overwrite the elements we are still to insert. While dequeuing the elements, we start saving them from the end of the array, as this is the part that is being freed up by the heap. This means we want the largest element to be dequeued first. This is achieved by simply using a comparator that is the opposite of the one that is passed. We add this static method to our ArrayHeap class:

public static <E> void heapSort(E[] array, Comparator<E> comparator){

    ArrayHeap<E> arrayHeap = new ArrayHeap<E>(0, (a,b) -> comparator.compare(b,a));


    arrayHeap.store...
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 £16.99/month. Cancel anytime