Home > Java > javaTutorial > body text

Heap Sort In Java

王林
Release: 2024-08-30 15:31:20
Original
493 people have browsed it

Heapsort in Java is a comparison based sorting technique, where data structure Binary Heap is used. This sorting is almost the same as that of selection sort, where the largest element will be selected, and places in the end, and the process will be repeated for all the elements. In order to understand Heap Sort, let us see what Binary Heap Sort in Java.

  • Tree-based Data Structure.
  • Complete Binary Tree.
  • It can have up to two children.
  • Value in the root node can be greater(Max Heap) or Smaller (Min Heap)

How does Heap Sort work in Java?

Before moving to the algorithm, let us see what Heapify is.

ADVERTISEMENT Popular Course in this category JAVA MASTERY - Specialization | 78 Course Series | 15 Mock Tests

Heapify

After a heap is created with the input data, the heap property may not be satisfied. To achieve it, a function called heapify will be used to adjust the heap nodes. If we want to create a max heap, the current element will be compared with its children, and if the value of children is greater than the current element, swapping will be done with the largest element in a left or right child. Similarly, if min-heap needs to be created, swapping will be done with the smallest element in the left or right child. For Example, The following is our input array,

Heap Sort In Java

We can consider this as a tree instead of an Array. The first element will be the root; the second will be the left child of the root; the third element will be the right child of the root, and so on.

Heap Sort In Java

In order to transform the heap into a tree, traverse the tree in a bottom-up direction. Since the leaf nodes do not have children, let us look into the next level. i.e. is 5 and 7.

Heap Sort In Java

We can begin at 5 as it is on the left. Here, 5 has two children: 9 and 4, where 9 is greater than the parent node 5. To make parents larger, we will swap 5 and 9. After swapping, the tree will be as shown below.

Heap Sort In Java

Let us move to the next element, 7, where 8 and 2 are the children. Similar to the elements 9 and 4, 7 and 8 will be swapped as in the below tree.

Heap Sort In Java

Finally, 3 has two children-9 and 8, where 9 is greater among the children and root. So, swapping of 3 and 9 will be done to make the root greater. Repeat the process until a valid heap is formed, as shown below.

Heap Sort In Java

Algorithm for Heap Sort in Ascending Order

  1. Create a Max Heap with the input data
  2. Replace the last element with the largest element in the heap
  3. Heapify the Tree
  4. Repeat the process until the array is sorted

Algorithm for Heap Sort in Descending Order

  1. Create a Min Heap with the input data
  2. Replace the last element with the smallest element in the heap
  3. Heapify the Tree
  4. Repeat the process until the array is sorted

Now, let us try to sort the above-obtained Heap in ascending order using the given algorithm. First, remove the largest element. i.e. root and replace it with the last element.

Heap Sort In Java

Now, heapify the tree formed and insert the removed element in the last of the array, as shown below.

Heap Sort In Java

Again, remove the root element, replace it with the last element and Heapify it.

Heap Sort In Java

Insert the removed element to the vacant position. Now you can see that the end of the array is being sorted.

Heap Sort In Java

Now, Remove element 7 and replace it with 2.

Heap Sort In Java

Heapify the tree, as shown below.

Heap Sort In Java

Repeat the process until the array is sorted. Removing element 5.

Heap Sort In Java

Heapifying the tree.

Heap Sort In Java

Removing element 4.

Heap Sort In Java

Heapfying again. 

Heap Sort In Java

At last, a sorted array like this will be formed.

Heap Sort In Java

Examples

Now, let us see the source code of Heap Sort in Java

//Java program to sort the elements using Heap sort
import java.util.Arrays;
public class HeapSort {
public void sort(int array[]) {
int size = array.length; //Assigning the length of array in a variable
// Create heap
for (int i = size / 2 - 1; i >= 0; i--)
heapify(array, size, i);
//Find the maximum element and replace it with the last element in the array
for (int i=size-1; i>=0; i--) {
int x = array[0];//largest element(It is available in the root)
array[0] = array[i];
array[i] = x;
// Recursively call <u>heapify</u> until a heap is formed
heapify(array, i, 0);
}
}
// <u>Heapify</u> function
void heapify(int array[], int SizeofHeap, int i) {
int largestelement = i; // Set largest element as root
int leftChild  = 2*i + 1; // index of left child = 2*i + 1
int rightChild  = 2*i + 2; //index of right child  = 2*i + 2
// left child is greater than root
if (leftChild  < SizeofHeap && array[leftChild ] > array[largestelement])
largestelement = leftChild ;
//right child is greater than largest
if (rightChild  < SizeofHeap && array[rightChild ] > array[largestelement])
largestelement = rightChild ;
// If <u>largestelement</u> is not root
if (largestelement != i) {
int temp = array[i];
array[i] = array[largestelement];
array[largestelement] = temp;
// Recursive call to  heapify the sub-tree
heapify(array, SizeofHeap, largestelement);
}
}
public static void main(String args[]) {
int array[] = {3,5,7,9,4,8,2};
System.<em>out</em>.println("Input array is: " + Arrays.<em>toString</em>(array));
HeapSort obj = new HeapSort();
obj.sort(array);
System.<em>out</em>.println("Sorted array is : " + Arrays.<em>toString</em>(array));
}
}
Copy after login

Output
Heap Sort In Java

Conclusion

Heap Sort is a sorting technique that depends on the Binary Heap Data structure. It is almost similar to selection sort and does not use separate arrays for sorting and heap.

 Recommended Articles

This has been a guide to Heap Sort in Java. Here we discuss the working, Sorting Algorithm with Ascending and Descending Order and examples with sample code. You can also go through our other suggested articles to learn more –

  1. Merge Sort In Java
  2. Heap Sort in C
  3. Heap Sort in C++
  4. Selection Sort in Data Structure

The above is the detailed content of Heap Sort In Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template