Skip to content

Commit e8b0e98

Browse files
Merge pull request #227 from aarxshi/main
Add Heap Sort implementation in Java
2 parents 9363ed2 + 1c63181 commit e8b0e98

1 file changed

Lines changed: 72 additions & 0 deletions

File tree

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
/**
2+
* Algorithm: Heap Sort
3+
* Description: Implementation of Heap Sort algorithm using binary heap
4+
* Time Complexity: O(n log n) for all cases
5+
* Space Complexity: O(1) (in-place)
6+
*/
7+
import java.util.Scanner;
8+
public class HeapSort {
9+
10+
public static int[] arrInput(Scanner sc) {
11+
System.out.print("Enter the size of the array: ");
12+
int n = sc.nextInt();
13+
int[] arr = new int[n];
14+
System.out.println("Enter the elements of the array: ");
15+
for (int i = 0; i < n; i++) {
16+
arr[i] = sc.nextInt();
17+
}
18+
return arr;
19+
}
20+
21+
public static void heapSort(int[] arr) {
22+
int n = arr.length;
23+
// Build max heap
24+
for (int i = n / 2 - 1; i >= 0; i--) {
25+
heapify(arr, n, i);
26+
}
27+
// Extract elements from heap
28+
for (int i = n - 1; i >= 0; i--) {
29+
// Swap current root with end
30+
int temp = arr[0];
31+
arr[0] = arr[i];
32+
arr[i] = temp;
33+
// Heapify reduced heap
34+
heapify(arr, i, 0);
35+
}
36+
}
37+
38+
public static void heapify(int[] arr, int n, int i) {
39+
int largest = i;
40+
int left = 2 * i + 1;
41+
int right = 2 * i + 2;
42+
if (left < n && arr[left] > arr[largest]) {
43+
largest = left;
44+
}
45+
if (right < n && arr[right] > arr[largest]) {
46+
largest = right;
47+
}
48+
if (largest != i) {
49+
int swap = arr[i];
50+
arr[i] = arr[largest];
51+
arr[largest] = swap;
52+
heapify(arr, n, largest);
53+
}
54+
}
55+
56+
public static void main(String[] args) {
57+
Scanner sc = new Scanner(System.in);
58+
int[] arr = arrInput(sc);
59+
System.out.print("Array before sorting: ");
60+
for (int num : arr) {
61+
System.out.print(num + " ");
62+
}
63+
System.out.println();
64+
heapSort(arr);
65+
System.out.print("Array after sorting: ");
66+
for (int num : arr) {
67+
System.out.print(num + " ");
68+
}
69+
System.out.println();
70+
sc.close();
71+
}
72+
}

0 commit comments

Comments
 (0)