-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeapSort.java
More file actions
67 lines (55 loc) · 1.88 KB
/
Copy pathHeapSort.java
File metadata and controls
67 lines (55 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
public class HeapSort {
public static void main(String[] args) {
int a[] = { 1, 232, 32595, 15495, 6294, 2, 56223, 295623, 326, 6, 18, 495, 89 };
heapsort(a);
for (int i : a) {
System.out.print(i + " ");
}
}
public static void heapsort(int arr[]) {
int n = arr.length;
// Step 1: Build max heap
buildmaxheap(arr);
// Step 2: Extract elements from heap one by one
for (int i = n - 1; i > 0; i--) {
// Move the current root (maximum) to the end
swap(arr, 0, i);
// Call heapify on the reduced heap
heapify(arr, i, 0);
}
}
// Heapify a subtree rooted with node i, n is size of heap
public static void heapify(int arr[], int n, int i) {
int maxindex = i;
int leftchild = 2 * i + 1;
int rightchild = 2 * i + 2;
// If left child is larger than root
if (leftchild < n && arr[leftchild] > arr[maxindex]) {
maxindex = leftchild;
}
// If right child is larger than maxindex
if (rightchild < n && arr[rightchild] > arr[maxindex]) {
maxindex = rightchild;
}
// If maxindex is not root
if (maxindex != i) {
swap(arr, i, maxindex);
// Recursively heapify the affected subtree
heapify(arr, n, maxindex);
}
}
// Swap two elements in the array
public static void swap(int arr[], int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
// Build a max heap from the array
public static void buildmaxheap(int arr[]) {
int n = arr.length;
// Build heap (rearrange the array)
for (int i = n / 2 - 1; i >= 0; i--) {
heapify(arr, n, i);
}
}
}