forked from kennyledet/Algorithm-Implementations
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeap.java
More file actions
62 lines (52 loc) · 1.08 KB
/
Heap.java
File metadata and controls
62 lines (52 loc) · 1.08 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
/*
* Written by: Rafael A. Rivera Soto
* Last Updated: January 2, 2014
*
* This class only contains the necessary methods needed to build a maxHeap and sort
* our array. It is in no way representative of a real heap implementation.
*/
public class Heap {
int [] array;
int size;
public Heap(int[] array) {
this.array = array;
this.size = array.length;
buildMaxHeap();
}
public int leftIndex(int i){
return 2*i + 1;
}
public int rightIndex(int i){
return 2*i + 2;
}
public void swap(int index1, int index2){
int temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
}
public void maxHeapify(int i){
int l = leftIndex(i);
int r = rightIndex(i);
int largest;
if(l < size && array[l] > array[i]){
largest = l;
}else{
largest = i;
}
if(r < size && array[r] > array[largest]){
largest = r;
}
if(largest != i){
swap(i,largest);
maxHeapify(largest);
}
}
public void buildMaxHeap(){
for(int i = size/2 - 1; i >= 0; i--){
maxHeapify(i);
}
}
public int[] getArray(){
return array;
}
}