代码参考 --《Java语言程序设计(进阶篇) 第八版》--chapter 24 排序
【背景知识】
【泛型类函数的定义】
定义泛型类:泛型参数在类名之后 public class GenericStack<E>{类内容}
定义泛型方法:泛型参数在返回类型之前 public static <E extends GeometricObject> void equalArea{ }
Heap 特征:
1 除了最后一层叶子节点可能不满,且都是偏左放置以外,其他层节点都是满的
1 父节点的值大于等于它的任意一个孩子
//但是左孩子和右孩子之间大小不确定!!!!!!!
【代码相关】
Heap中添加节点:
按照从上到下 从左到右添加。若新插入的值大于其对应的父节点,则逐步向上替换父节点与他的值,知道达到Heao 的要求
Heap 中删除节点:
1 把根节点删除,然后将最后一个节点删除,并赋给根节点处的值
2 比较新加入的根节点与左右孩子的最大值,将该节点与最大孩子值替换,然后依次类推下去。
import java.util.ArrayList;
import org.omg.CosNaming.NamingContextExtPackage.AddressHelper;
public class Heap <E extends Comparable>{
ArrayList<E> list=new ArrayList<E>();
public Heap(){
}
public Heap(E[] Objects){
for(int i=0;i<Objects.length;i++)
add(Objects[i]);
}
public void add(E newObject) {
// TODO Auto-generated method stub
list.add(newObject);
int currentIndex=list.size()-1;
while(currentIndex>0){
int parentIndex=(currentIndex-1)/2;
if(list.get(currentIndex).compareTo(list.get(parentIndex))>0)
{
E temp=list.get(currentIndex);
list.set(currentIndex, list.get(parentIndex));
list.set(parentIndex, temp);
}
else
break;
currentIndex=parentIndex;
}
}
public E remove() {
if(list.size()==0)
return null;
E removedObject=list.get(0);
list.set(0, list.get(list.size()-1));
list.remove(list.size()-1);
int currentIndex=0;
while(currentIndex<list.size()){
int leftChildIndex=2*currentIndex+1;
int rightChildIndex=2*currentIndex+2;
if(leftChildIndex>=list.size())
break;
//否则从左边找出最大的节点数值
int maxIndex=leftChildIndex;
if(rightChildIndex<list.size()){
if(list.get(maxIndex).compareTo(list.get(rightChildIndex))<0)
maxIndex=rightChildIndex;
}
if(list.get(currentIndex).compareTo(list.get(maxIndex))<0){
E temp=list.get(maxIndex);
list.set(maxIndex, list.get(currentIndex));
list.set(currentIndex, temp);
currentIndex=maxIndex;
}
else
break;
}
return removedObject;
}
}
2 heapSort 运行及结果:
public class HeapSort {
public static void main(String[] args){
Integer[] list={2,3,2,2,5,6,1,-2,3,14,12};
//HeapSort heapSort=new HeapSort();
HeapSort(list);
for(int i=0;i<list.length;i++){
System.out.print(list[i]+" ");
}
}
public static<E extends Comparable> void HeapSort(E[] list) {
// TODO Auto-generated constructor stub
Heap<E> heap=new Heap<E>();
for(int i=0;i<list.length;i++)
heap.add(list[i]);
for(int i=list.length-1;i>=0;i--)
list[i]=heap.remove();
}
}
运行结果:
-2 1 2 2 2 3 3 5 6 12 14