Skip to content

Commit

Permalink
Дерево
Browse files Browse the repository at this point in the history
  • Loading branch information
Pastor committed Dec 6, 2024
1 parent e17c469 commit cc1393c
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 11 deletions.
28 changes: 22 additions & 6 deletions vol6/src/main/java/ru/mifi/practice/vol6/tree/Heap.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package ru.mifi.practice.vol6.tree;

import java.util.Arrays;

public interface Heap<T extends Comparable<T>> {

T deleteRoot();
Expand All @@ -12,9 +14,11 @@ public interface Heap<T extends Comparable<T>> {

void print();

int size();

final class Minimum<T extends Comparable<T>> implements Heap<T> {
public static final String FORMAT = "%5s %5s %5s%n";
private static final int TOP = 1;
private static final int TOP = 0;
private final Object[] heap;
private final int capacity;
private int size;
Expand Down Expand Up @@ -66,8 +70,9 @@ public Heap<T> add(T value) {
if (size >= capacity) {
return this;
}
heap[++size] = value;
heap[size] = value;
int current = size;
++size;

while (compare(current, positionParent(current)) < 0) {
swap(current, positionParent(current));
Expand All @@ -86,26 +91,32 @@ public void refresh() {
@SuppressWarnings("unchecked")
@Override
public T deleteRoot() {
T pop = (T) heap[TOP];
heap[TOP] = heap[size--];
final T pop = (T) heap[TOP];
heap[TOP] = heap[size];
--size;
heapify(TOP);
return pop;
}

@SuppressWarnings("unchecked")
@Override
public T top() {
return (T) heap[0];
return (T) heap[TOP];
}

@Override
public void print() {
System.out.printf(FORMAT, "top", "left", "right");
for (int k = TOP; k <= size / 2; k++) {
System.out.printf(FORMAT, nullable(heap[k]), nullable(heap[2 * k]), nullable(heap[2 * k + 1]));
System.out.printf(FORMAT, nullable(heap[k]), nullable(heap[positionLeft(k) + 1]), nullable(heap[positionRight(k) + 1]));
}
}

@Override
public int size() {
return size;
}

@SuppressWarnings("unchecked")
private int compare(int position1, int position2) {
Object left = heap[position1];
Expand All @@ -127,5 +138,10 @@ private static Object nullable(Object value) {
}
return value;
}

@Override
public String toString() {
return Arrays.toString(heap);
}
}
}
12 changes: 7 additions & 5 deletions vol6/src/main/java/ru/mifi/practice/vol6/tree/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -70,10 +70,12 @@ public static void main(String[] args) throws IOException {
.add(21);
heap.refresh();
heap.print();
System.out.print(" MIN: ");
System.out.println(heap.top());
System.out.print(" DEL: ");
System.out.println(heap.deleteRoot());
heap.print();
for (int i = 0; i < 5; i++) {
System.out.print(" MIN: ");
System.out.println(heap.top());
System.out.print(" DEL: ");
System.out.println(heap.deleteRoot());
heap.print();
}
}
}

0 comments on commit cc1393c

Please sign in to comment.