-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
trying to implement some stuff from data structures class
- Loading branch information
Showing
2 changed files
with
60 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
public class BinaryHeap<T> { | ||
private DynamicResizingArray<T> array = new DynamicResizingArray<T>(); | ||
|
||
public BinaryHeap() { | ||
// nothing | ||
} | ||
|
||
public T extractMax() { | ||
return null; // TODO | ||
} | ||
|
||
public void insert(T item) { | ||
// put it at the end and then swap up with parent as much as needed for heap property | ||
// TODO | ||
} | ||
|
||
public static void main(String[] args) { | ||
BinaryHeap heap = new BinaryHeap(); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
public class DynamicResizingArray<T> { | ||
private T[] array = (T[]) new Object[1]; | ||
private int capacity = 1; | ||
public int length = 0; | ||
|
||
public DynamicResizingArray() { | ||
// nothing | ||
} | ||
|
||
public void insert(T item) { | ||
array[length] = item; | ||
length++; | ||
resize(); | ||
} | ||
|
||
private void resize() { | ||
if (length == capacity) { | ||
// resize to double | ||
int newCapacity = 2 * capacity; | ||
T[] newArray = (T[]) new Object[newCapacity]; | ||
copyItems(array, newArray); | ||
array = newArray; | ||
} | ||
} | ||
|
||
private void copyItems(T[] array, T[] newArray) { | ||
for (int i = 0; i < array.length; i++) { | ||
newArray[i] = array[i]; | ||
} | ||
} | ||
|
||
public void push(T item) { | ||
int index = length; | ||
setItem(index, item); | ||
} | ||
|
||
public void setItem(int index, T item) { | ||
array[index] = item; | ||
} | ||
} |