-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexHeap.java
More file actions
100 lines (84 loc) · 1.98 KB
/
Copy pathexHeap.java
File metadata and controls
100 lines (84 loc) · 1.98 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package GenderMag2;
import java.util.ArrayList;
public class exHeap<T> implements DMQueue<T>{
//priority queue
//create a heap
ArrayList<T> heap;
//compare
private int compare(T x, T y) {
if (x == null && y == null) {
return 0;
}
if (x == null) {
return -1;
}
if (y == null) {
return 1;
}
return ((Comparable<T>) x).compareTo(y);
}
//swap
private void swap(int song1, int song2) {
T temp = heap.get(song1);
heap.set(song1, heap.get(song2));
heap.set(song2, temp);
}
@Override
public void addSong(Object song) {
// insertion
}
@Override
public void deleteAll() {
// TODO Auto-generated method stub
}
@Override
public boolean isEmpty() {
// TODO Auto-generated method stub
return false;
}
@Override
public T peekSong() {
if (heap.isEmpty()) {
return (T) "heap is empty"; //or null ig
}
return heap.get(0);
}
@Override
public void pushSong(Object song) {
// TODO Auto-generated method stub
}
@Override
public T removeSong() {
if (isEmpty()) {
System.out.println("Heap is empty");
return null;
}
T root = heap.get(0);
T last = heap.remove(heap.size() - 1);
if (!heap.isEmpty()) {
heap.set(0, last);
heapifyDown(0);
}
return root;
}
private void heapifyDown(int index) {
int leftIndex = 2 * index + 1;
int rightIndex = 2 * index + 2;
int largestIndex = index;
if (leftIndex < heap.size() && compare(heap.get(leftIndex), heap.get(largestIndex)) > 0) {
largestIndex = leftIndex;
}
if (rightIndex < heap.size() && compare(heap.get(rightIndex), heap.get(largestIndex)) > 0) {
largestIndex = rightIndex;
}
if (largestIndex != index) {
swap(index, largestIndex);
heapifyDown(largestIndex);
}
}
@Override
public int size() {
// TODO Auto-generated method stub
return 0;
}
}