Skip to content
This repository was archived by the owner on Jun 2, 2024. It is now read-only.

Commit 56cee64

Browse files
authored
Merge pull request #4 from pojith/pojith-patch-4
Heap sort
2 parents e9eecd3 + c09d2c3 commit 56cee64

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
import java.util.Arrays;
2+
import java.util.InputMismatchException;
3+
import java.util.Scanner;
4+
5+
public class HeapSort {
6+
7+
// Function to perform heap sort
8+
public static void heapSort(int[] arr) {
9+
int n = arr.length;
10+
11+
// Build heap (rearrange array)
12+
for (int i = n / 2 - 1; i >= 0; i--) {
13+
heapify(arr, n, i);
14+
}
15+
16+
// One by one extract an element from heap
17+
for (int i = n - 1; i > 0; i--) {
18+
// Move current root to end
19+
int temp = arr[0];
20+
arr[0] = arr[i];
21+
arr[i] = temp;
22+
23+
// call max heapify on the reduced heap
24+
heapify(arr, i, 0);
25+
}
26+
}
27+
28+
// To heapify a subtree rooted with node i which is an index in arr[]
29+
public static void heapify(int[] arr, int n, int i) {
30+
int largest = i; // Initialize largest as root
31+
int l = 2 * i + 1; // left = 2*i + 1
32+
int r = 2 * i + 2; // right = 2*i + 2
33+
34+
// If left child is larger than root
35+
if (l < n && arr[l] > arr[largest]) {
36+
largest = l;
37+
}
38+
39+
// If right child is larger than largest so far
40+
if (r < n && arr[r] > arr[largest]) {
41+
largest = r;
42+
}
43+
44+
// If largest is not root
45+
if (largest != i) {
46+
int swap = arr[i];
47+
arr[i] = arr[largest];
48+
arr[largest] = swap;
49+
50+
// Recursively heapify the affected sub-tree
51+
heapify(arr, n, largest);
52+
}
53+
}
54+
55+
public static void main(String[] args) {
56+
Scanner scanner = new Scanner(System.in);
57+
58+
try {
59+
System.out.print("Enter the number of elements: ");
60+
int n = scanner.nextInt();
61+
if (n <= 0) {
62+
throw new IllegalArgumentException("Number of elements must be positive.");
63+
}
64+
65+
int[] arr = new int[n];
66+
67+
System.out.println("Enter the elements:");
68+
for (int i = 0; i < n; i++) {
69+
arr[i] = scanner.nextInt();
70+
}
71+
72+
System.out.println("Original array: " + Arrays.toString(arr));
73+
74+
heapSort(arr);
75+
76+
System.out.println("Sorted array: " + Arrays.toString(arr));
77+
} catch (InputMismatchException e) {
78+
System.out.println("Invalid input. Please enter integers only.");
79+
} catch (IllegalArgumentException e) {
80+
System.out.println(e.getMessage());
81+
} finally {
82+
scanner.close();
83+
}
84+
}
85+
}

0 commit comments

Comments
 (0)