Docsity

Java Code for Heap Sort, Study notes of Data Structures and Algorithms

Toggle sidebar
bg1
Problem statement:
Implement the Heap/shell sort algorithm implemented in JAVA demonstrating
heap/shell data structure with modularity of programming language.
// Java program for implementation of Heap Sort
public class HeapSort
{
public void sort(int arr[])
{
int n = arr.length; // 6
// Build heap (rearrange array)
//Total Nodes = 6.
//Last Non-leaf node index = (6/2) - 1 = 2
//Therefore, last non-leaf node = 3
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
// One by one extract an element from heap
for (int i=n-1; i>=0; i--)
{
// Move current root to end
int temp = arr[0];
arr[0] = arr[i];
pf3
pf4

Partial preview of the text

Download Java Code for Heap Sort and more Study notes Data Structures and Algorithms in PDF only on Docsity!

Problem statement: Implement the Heap/shell sort algorithm implemented in JAVA demonstrating heap/shell data structure with modularity of programming language. // Java program for implementation of Heap Sort public class HeapSort { public void sort(int arr[]) { int n = arr.length; // 6 // Build heap (rearrange array) //Total Nodes = 6. //Last Non-leaf node index = ( 6 /2) - 1 = 2 //Therefore, last non-leaf node = 3 for (int i = n / 2 - 1; i >= 0; i--) heapify(arr, n, i); // One by one extract an element from heap for (int i=n-1; i>=0; i--) { // Move current root to end int temp = arr[0]; arr[0] = arr[i];

arr[i] = temp; // call max heapify on the reduced heap heapify(arr, i, 0); } } // To heapify a subtree rooted with node i which is an index in arr[]. n is size of heap void heapify(int arr[], int n, int i) { int largest = i; // Initialize largest as root int l = 2i + 1; // left = 2i + 1 int r = 2i + 2; // right = 2i + 2 // If left child is larger than root if (l < n && arr[l] > arr[largest]) largest = l; // If right child is larger than largest so far if (r < n && arr[r] > arr[largest]) largest = r;

// Driver program public static void main(String args[]) { int arr[] = { 4 , 3 , 7 , 1 , 8 , 5 }; int n = arr.length; HeapSort ob = new HeapSort(); ob.sort(arr); System.out.println("Sorted array is"); printArray(arr); } }