2 Star 0 Fork 0

CS-IMIS-23 / 20172309_javaProgramming

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
BigArraryHeap.java 2.93 KB
一键复制 编辑 原始数据 按行查看 历史
20172309 提交于 2018-11-09 13:04 . 11.9 大顶堆 的实验类
package second_term.tweflth_chapter;
import second_term.first_week.EmptyCollectionException;
public class BigArraryHeap<T> extends ArrayBinaryTree<T> implements BigHeapADT<T> {
int a =1;
public BigArraryHeap(){
super();
}
@Override
public void addElement(T objc) {
if (count == tree.length)
expandCapacity();
tree[count] = objc;
count=count+1;
modCount++;
if (count > 1)
heapifyAdd();
}
private void heapifyAdd() {
T temp;
int next = count - 1;
temp = tree[next];
while ((next != 0) &&
(((Comparable)temp).compareTo(tree[(next-1)/2]) > 0))
{
tree[next] = tree[(next-1)/2];
next = (next-1)/2;
}
tree[next] = temp;
// System.out.println("第"+a+"次排序:");
// for (int i =0;i<tree.length;i++){
// if (tree[i]!=null)
// System.out.print(tree[i]+" ");}
// System.out.println();
// a++;
}
@Override
public T removeMax() throws EmptyCollectionException {
if (isEmpty())
throw new EmptyCollectionException("ArrayHeap");
T maxElement = tree[0];
tree[0] = tree[count-1];
heapifyRemove();
count--;
modCount--;
return maxElement;
}
private void heapifyRemove() {
T temp;
int node = 0;
int left = 1;
int right = 2;
int next;
if ((tree[left] == null) && (tree[right] == null))
next = count;
else if (tree[right] == null)
next = left;
else if (((Comparable)tree[left]).compareTo(tree[right]) > 0)
next = left;
else
next = right;
temp = tree[node];
while ((next < count) &&
(((Comparable)tree[next]).compareTo(temp) > 0))
{
tree[node] = tree[next];
node = next;
left = 2 * node + 1;
right = 2 * (node + 1);
if ((tree[left] == null) && (tree[right] == null))
next = count;
else if (tree[right] == null)
next = left;
else if (((Comparable)tree[left]).compareTo(tree[right]) > 0)
next = left;
else
next = right;
}
tree[node] = temp;
}
@Override
public T findMax() {
if (isEmpty())
throw new EmptyCollectionException("ArrayHeap");
return tree[0];
}
public void sorting()
{
int i = count;
while (i > 0)
{
removeMax();
i--;
System.out.println(toString());
}
}
public String toString()
{
String result = "";
for (int i = 0; i < tree.length; i++)
{
if (tree[i] != null)
result += tree[i] + " ";
}
return result;
}
}
Java
1
https://gitee.com/CS-IMIS-23/20172309_javaProgramming.git
git@gitee.com:CS-IMIS-23/20172309_javaProgramming.git
CS-IMIS-23
20172309_javaProgramming
20172309_javaProgramming
e0db3386aa72b6df60674c2eb2b771e53d373766

搜索帮助