Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
11 views2 pages

Heap Sort Java

The document contains a Java implementation of the Heap Sort algorithm, which includes methods for heapifying a subtree, performing the heap sort, and printing the array. The main method demonstrates the sorting of an example array. The algorithm builds a max heap and then sorts the array by repeatedly extracting the maximum element.

Uploaded by

rachi.website
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views2 pages

Heap Sort Java

The document contains a Java implementation of the Heap Sort algorithm, which includes methods for heapifying a subtree, performing the heap sort, and printing the array. The main method demonstrates the sorting of an example array. The algorithm builds a max heap and then sorts the array by repeatedly extracting the maximum element.

Uploaded by

rachi.website
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

public class HeapSort {

// Method to heapify a subtree rooted at index i


static void heapify(int[] arr, int n, int i) {
int largest = i; // Initialize largest as root
int left = 2 * i + 1; // Left child
int right = 2 * i + 2; // Right child

// If left child is larger than root


if (left < n && arr[left] > arr[largest]) {
largest = left;
}

// If right child is larger than largest so far


if (right < n && arr[right] > arr[largest]) {
largest = right;
}

// If largest is not root


if (largest != i) {
// Swap arr[i] and arr[largest]
int temp = arr[i];
arr[i] = arr[largest];
arr[largest] = temp;

// Recursively heapify the affected subtree


heapify(arr, n, largest);
}
}

// Method to perform heap sort


static void heapSort(int[] arr) {
int n = arr.length;

// Build a max heap


for (int i = n / 2 - 1; i >= 0; i--) {
heapify(arr, n, i);
}

// One by one extract elements 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 heapify on the reduced heap


heapify(arr, i, 0);
}
}

// Method to print the array


static void printArray(int[] arr) {
for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
}
public static void main(String[] args) {
int[] arr = {12, 11, 13, 5, 6, 7};

System.out.println("Original array:");
printArray(arr);

heapSort(arr);

System.out.println("Sorted array:");
printArray(arr);
}
}

You might also like