-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathHeapGabrielR.java
More file actions
81 lines (70 loc) · 1.75 KB
/
HeapGabrielR.java
File metadata and controls
81 lines (70 loc) · 1.75 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
public class HeapGabrielR{
private int [] heap;
private int [] heapSorted;
private int positionsChanged;
//Heap Constructor
public Heap(int [] heap){
this.heap = heap;
this.heapConstruction();
}
private void heapConstruction(){
int left = (heap.length/2) + 1;
while(left > 1){
left--;
this.maintanceHeap(left,heap.length);
}
}
//Adjust the actual node passed by parameter
private void maintanceHeap(int actualNode , int heapSize){
int leftSon = actualNode*2;
int value = this.heap[actualNode];
while(leftSon <= heapSize){
if((leftSon < heapSize) && this.heap[leftSon+1] > this.heap[leftSon])
leftSon++;
if(value >= this.heap[leftSon-1])
break;
this.heap[actualNode] = this.heap[leftSon-1];
actualNode = leftSon;
leftSon = actualNode*2;
positionsChanged++;
}
this.heap[actualNode-1] = value;
}
//Remove the register with the highest value in heap and reorganize
private int removeMax(int heapSize){
int max = 0;
if(heapSize < 1)
System.out.println("Erro: empty heap");
else{
max = this.heap[1];
this.heap[1] = this.heap[heapSize-1];
positionsChanged++;
this.maintanceHeap(1, heapSize);
}
return max;
}
//Build the heap with the father being bigger than two sons
public void heapsort(int [] heap , int heapSize){
int actualNode;
int heapSizeAux = heapSize;
this.heapConstruction();
actualNode = 1;
while ( heapSizeAux > 1){
this.heap[heapSizeAux-1] = this.removeMax(heapSizeAux);
heapSizeAux --;
}
setHeapSorted(heap);
}
public int[] getHeap(){
return this.heap;
}
public int[] getHeapSorted(){
return this.heapSorted;
}
public void setHeapSorted(int[] heap){
heapSorted = this.heap;
}
public int getPositionsChanged(){
return this.positionsChanged;
}
}