Hashmap Data Structures
Hashmap Data Structures
HW #7
4/17/23
1.
Questions 1 and 2
3. Question 3
a.
b.
4. Question 4
a. public BinaryNode < T > getNode(int pos) {
b. if (pos < 1) {
c. System.out.println("invalid position");
d. return null;
e. }
f.
g. int sizeOfList = (int)(Math.log(pos) / Math.log(2));
h. boolean[] islefts = new boolean[sizeOfList];
i. BinaryNode < T > currentNode = root;
j. int currentPos = pos;
k.
l. for (int i = islefts.length - 1; i >= 0; i--) {
m. if (currentPos % 2 == 0) {
n. islefts[i] = true;
o. } else {
p. islefts[i] = false;
q. }
r. currentPos /= 2;
s. }
t.
u. for (int i = 0; i < islefts.length; i++) {
v. if (islefts[i] == true) {
w. currentNode = currentNode.leftChild;
x. } else {
y. currentNode = currentNode.rightChild;
z. }
aa. }
bb. return currentNode;
cc. }
5. Question 5
a. The min element is simply the root. The max element is one of the child’s of root
so comparing to see which is bigger returns the max element.
b. public void insert(int newElement) { (check)
c. int depth = (int)(Math.log(pos) / Math.log(2));
d. int[] heap = {0,-5,4,1,null,null,null,null,null};
e. int currentpos;
f. boolean satisfied = false;
g.
h. for (int i = 1; i < heap.length; i++) {
i. if (heap[i] == null) {
j. currentpos = i;
k. heap[i] = newElement;
l. break;
m. }
n. }
o.
p. while (!satisfied) {
q. if (depth % 2 == 0) {
r. if (heap[i / 2].value < heap[currentpos].value) {
s. tmp = heap[i / 2];
t. heap[i / 2] = heap[currentpos];
u. heap[currentpos] = tmp;
v. currentpos = i / 2;
w. depth -= 1;
x. } else if (heap[i / 4].value > heap[currentpos].value) {
y. tmp = heap[i / 4];
z. heap[i / 4] = heap[currentpos];
aa. heap[currentpos] = tmp;
bb. currentpos = i / 4;
cc. depth -= 2;
dd. } else {
ee. satisfied = true;
ff. }
gg. } else {
hh. if (heap[i / 2].value > heap[currentpos].value) {
ii. tmp = heap[i / 2];
jj. heap[i / 2] = heap[currentpos];
kk. heap[currentpos] = tmp;
ll. currentpos = i / 2;
mm. depth -= 1;
nn. } else if (heap[i / 4].value < heap[currentpos].value) {
oo. tmp = heap[i / 4];
pp. heap[i / 4] = heap[currentpos];
qq. heap[currentpos] = tmp;
rr. currentpos = i / 4;
ss. depth -= 2;
tt. } else {
uu. satisfied = true;
vv. }
ww. }
xx. }
yy.
zz. }
6.