-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeapSort.java
More file actions
54 lines (45 loc) · 1.49 KB
/
HeapSort.java
File metadata and controls
54 lines (45 loc) · 1.49 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
package kb.sort;
import kb.sort.api.Sortable;
public class HeapSort implements Sortable {
/**
* Heap Sort.
* O(n.log(n)) time.
* O(1) space.
* Stable: No but can be made stable.
*/
@Override
public int[] sort(int[] arr) {
// 1. First heapify the hole tree: every parent is grater than it's children
for (int i = 2 * arr.length - 1; i >= 0; i--)
heapify(arr, i, arr.length);
// When the Max Heap is created he max value is the at the beginning of the array.
// 2. Swap the first and the last element and decrease the heap size with 1.
// 3. Call heapify to the reduced heap.
for (int i = arr.length - 1; i >= 0; i--) {
swap(arr, 0, i);
heapify(arr, 0, i);
}
return arr;
}
private void heapify(int[] arr, int start, int end) {
int greater = start;
int l = start * 2 + 1;
int r = start * 2 + 2;
if (l < end && r < end && arr[r] > arr[l] && arr[start] < arr[r])
greater = r;
else if (l < end && arr[start] < arr[l])
greater = l;
if (start != greater) {
swap(arr, start, greater);
heapify(arr, greater, end);
}
}
private void swap(int[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}