- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to perform heapsort on an array in Java?
Following is the algorithm for heapsort (maxheap).
Step 1 − Create a new node at the end of the heap.
Step 2 − Assign new value to the node.
Step 3 − Compare the value of this child node with its parent.
Step 4 − If the value of parent is less than a child, then swap them.
Step 5 − Repeat step 3 & 4 until Heap property holds.
Example
import java.util.Arrays; import java.util.Scanner; public class Heapsort { public static void heapSort(int[] myArray, int length) { int temp; int size = length-1; for (int i = (length / 2); i >= 0; i--) { heapify(myArray, i, size); }; for(int i= size; i>=0; i--) { temp = myArray[0]; myArray[0] = myArray[size]; myArray[size] = temp; size--; heapify(myArray, 0, size); } System.out.println(Arrays.toString(myArray)); } public static void heapify (int [] myArray, int i, int heapSize) { int a = 2*i; int b = 2*i+1; int largestElement; if (a<= heapSize && myArray[a] > myArray[i]) { largestElement = a; } else { largestElement = i; } if (b <= heapSize && myArray[b] > myArray[largestElement]) { largestElement = b; } if (largestElement != i) { int temp = myArray[i]; myArray[i] = myArray[largestElement]; myArray[largestElement] = temp; heapify(myArray, largestElement, heapSize); } } public static void main(String args[]) { Scanner scanner = new Scanner(System.in); System.out.println("Enter the size of the array :: "); int size = scanner.nextInt(); System.out.println("Enter the elements of the array :: "); int[] myArray = new int[size]; for(int i=0; i<size; i++) { myArray[i] = scanner.nextInt(); } heapSort(myArray, size); } }
Output
Enter the size of the array :: 5 Enter the elements of the array :: 45 125 44 78 1 [1, 44, 45, 78, 125]
- Related Articles
- How to perform binary search on an array in java?
- How do you perform an AND query on an array in MongoDB?
- How to perform arithmetic operations on two-dimensional array in C?
- How to perform an exchange on sushiswap Blockchain?
- How to perform mouseover action on an element in Selenium?
- How to perform double click on an element in Selenium?
- Java Program to perform an XOR on a set of Booleans
- Java Menu Driven Program to Perform Array Operation
- How to convert an object array to an integer array in Java?
- How to create an Array in Java?
- How to initialize an array in Java
- How to filter an array in Java
- How to empty an array in Java
- How to shuffle an array in Java?
- How to resize an array in Java?

Advertisements