-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeapSort.java
More file actions
38 lines (35 loc) · 1.13 KB
/
Copy pathHeapSort.java
File metadata and controls
38 lines (35 loc) · 1.13 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
import java.util.*;
public class HeapSort {
static ArrayList<Integer> heap_sort(ArrayList<Integer> arr) {
heapSort(arr, arr.size());
return arr;
}
static void heapify(ArrayList<Integer> arr, int n, int i){
// Collections.swap(arr, random, i);
int smallest = i; //init smallest root
int l = 2 * i +1; //lef side of heap
int r = 2 * i +2; //right side of heap
//if child is smaller than root
if ((l < n) && (arr.get(l) > arr.get(smallest))){
smallest = l;
}
if (r < n && arr.get(r) > arr.get(smallest)) {
smallest = r;
}
//if child is not root
if (smallest != i) {
int temp = arr.get(i);
Collections.swap(arr, i, smallest);
heapify(arr, n, smallest);
}
}
static void heapSort(ArrayList<Integer> arr, int n){
for(int i = n / 2 -1; i >= 0; i--){
heapify(arr, n, i);
}
for(int i = n -1; i >= 0; i--){
Collections.swap(arr, 0, i);
heapify(arr, i, 0);
}
}
}