×

Heap Sort in Java

In this section, we have discussed the max-heap for sorting the elements.

Max Heap Algorithm

Step 1: Build max heap for the given input array using the method heapify().

Step 2: swap the root with the last element of the array. Reduce the size of the heap by 1.

Step 3: Call the heapify() method again to maintain the property of max heap on remaining elements.

Step 4: Repeat steps 3 & 4 till the whole array gets sorted.

Pseudo Code

Java Program

The following Java program implements the heap sort using the pseudo-code explained above.

FileName: HeapSortExample.java

Output:

Explanation: The above program is imitating bubble sort. The heapify() method ensures that the maximum value element sits at the index 0. Then in one swap, the maximum element is put at the end of the array. When the heapify() method is called the second time, it puts the second maximum element at index 0.

The swapping process puts the second maximum element at the second last index of the array, and the process of invoking the heapify() method and swapping of elements continues till the whole array is sorted. The following diagram demonstrates the same.

Heap Sort in Java

Note that instead of using the max-heap, min-heap can also be used to sort. Using the min-heap, the heap sort resembles the selection sort as the root of the min-heap always gives the element of least value.

Analysis of the Heap Sort

Even though heap sort resembles the selection or bubble sort, the heap sort is much faster than the selection or bubble sort. However, similar to the selection or bubble sort, heap sort also divides the input array virtually into two halves; one is sorted, and another is unsorted.

Time Complexity

The heapify() method does the heapification process in O(log(n)) times, where n is the size of the input array. Also, the for-loop is iterating over each element of the array from right to left (see code). In each iteration, the heapify() method is invoked. Thus, for the for-loop time complexity is O(n) and O(log(n)) for the heapify() method. Hence, the total time complexity turns out to be O(n * log(n)) = O(nlog(n)). As O(nlog(n) is always less than O(n^2); therefore, heap sort is better than selection or bubble sort. One can think of the heap sorting algorithm as an improved version of selection sort or bubble sort.

Space Complexity

Similar to selection or bubble sort, heap sort algorithm also does the in-place sorting. The heap sort tries to visualize the input array as either min heap or max heap. Therefore, the space complexity for the heap sort turns out to be O(1), i.e., constant space for sorting the input array or list.

Conclusion

Heap sort works faster than bubble or selection sort. However, for larger data sets, it is found that merge sort is a better choice than heap sort, even though merge as well heap sort gives the time complexity of O(nlog(n)). Also, unlike merge sort, heap sort is not a stable sorting algorithm. However, by some modification, one can make merge sort stable. However, making heap sort stable increases the complexity of the algorithm.


Related Topics

Fibonacci Series Program in Java

Fibonacci Series Program in Java using Recursion Fibonacci series is a series whose every term is comprised of adding its previous two terms, barring the first two terms 0 and 1....

3 minutes read.

Compile-time Error in Java

In java, the execution of a program is stopped due to the occurrence of some problem known as an error. Errors are illegal operations that are carried out by the...

4 minutes read.

Java New Keyword

To create a class instance in Java, use the new keyword. In other words, it returns a reference to the memory that was allocated for a new object and instantiates...

3 minutes read.

Package naming convention in Java

It is conceivable that many programmers will use the same name for various types, given that Java programmers from all over the world create classes and interfaces. For illustration, suppose...

4 minutes read.

Java Null Keyword

Null is a term that is only used for literal values in Java. Although it appears to be a term, it is a literal opposite of true and false. Java's...

3 minutes read.

Difference between Abstract Class and Interface

There is a similarity between abstract class and interface is that we cannot create objects for both of them. But irrespective of this, there are some differences between them, let’s...

2 minutes read.

Differences between Lock and Monitor in Java Concurrency

In this tutorial, we will discuss the overview of Lock and Monitor and the differences between them. Introduction Java Concurrency is the ability to perform specific tasks at a time parallelly. The...

4 minutes read.

Java inheritance with Example

Java inheritance Java inheritance is a mechanism in which a child object acquires all the properties and behaviors of a parent object. It helps in reusing the code and establishes...

7 minutes read.

Java String getChars() Method

Java String getChars() method copies characters from current String to the destination character array . Syntax: public void getChars(int srcBeginIndex, int srcEndIndex, char[] destination, int dstBeginIndex) Parameters: srcBegin - index of the first character...

1 minute read.

Java IO

It is a part of java libraries but is often known as I/O streams, file I/O, and file handling. The Java I/O concept satisfies the need for input processing and...

4 minutes read.

Packages Program in java

Let us know what package is in the Java programming language, and later we will learn about types of packages and how to define a package. How to import Java...

4 minutes read.

How to Create a Generic List in Java?

Generics are types that have parameters. The goal is to make it possible for methods, classes, and interfaces to take type (Integer, String, etc., and user-defined types) as a parameter....

4 minutes read.

Types of Garbage Collector in Java

Garbage collection is a Java feature that offers automatic memory management. The JVM is in charge of it. The programmer does not have to handle object creation and deallocation. We...

3 minutes read.

Java Math max() Method

The max() method of Math class returns the greater of two arguments. The arguments can be of double, float, int or long data type. Syntax: public static double max(double a, double b)public...

2 minutes read.

Java Strings

String class is the most used class in Java programming language. The string is the sequence of characters, which is treated as objects in Java. Creating String objects We create String objects...

5 minutes read.

Java Integer hashCode() method

The hashCode()  method of Java Integer class returns a hash code for this Integer.  Syntax public int hashCode() public static int hashCode(int value)  Parameters The parameter ‘value’ represents a value whose hash code...

1 minute read.

Operators in Java

There is a good operator environment provided by Java. These operators are divided into four different groups i.e. arithmetic, bitwise, relational, and logical. There are other operators also available to...

7 minutes read.

Functional Interface in Java 8

A brief introduction to Interface in Java: Interfaces in Java are basically the blue print of classes. Before the appearance of Java 8, it was only possible to declare one or...

11 minutes read.

Access Modifier in Java

The access modifiers in java are used to change the accessibility and scope of a method, constructor, class, and fields. If you are aware of C++ language, when we declare any member...

2 minutes read.

Java Integer toBinaryString() method

The toBinaryString() method of Java Integer class returns a string representing the specified int argument as an unsigned integer in base 2. Syntax public static String toBinaryString (int  i)  Parameters The parameter ‘i’ represents...

1 minute read.