许多应用要用堆,比如,优先队列,即队列的扩充,队列的每个元素增加一个称为优先级的字段,优先队列可以是线性结构的,但要有较高的效率,应把它组织成堆结构。元素入队是,相当于执行堆的插入算法;但在队头每次删除的总是队顶具有最大优先级的元素,因此可以把它称为最大优先级队列。再比如,堆排序是选择排序中的一种典型排序,它也是利用堆来实现的,按非递增的次序排序要使用最小堆,而按非递减的次序排序要使用最大堆。
下面是实现堆排序的代码:
Lists类:线性表数据结构
HeapSort类:堆排序类
public class Lists {
private int maxSize=100;
private int[]heap;
private int count=0;
public Lists(){
heap=new int[maxSize];
}
public int getValue(int i){
return heap[i];
}
public void setValue(int i,int v){
heap[i]=v;
}
public void insert(int i,int x){
if(i<0 && i>count){
System.out.println("position error");
}
if(i>maxSize){
System.out.println("position overFolw");
}
for(int j=count-1;j>=i;j++){
heap[j+1]=heap[j];
}
heap[i]=x;
count++;
}
public void delete(int i){
if(i<0||i>=count){
System.out.println("没有该节点");
return;
}
for(int j=i;j<count-1;j++){
heap[j]=heap[j++];
}
count--;
}
public int length(){
return count;
}
public void countMinus(){
count--;
}
}
public class HeapSort {
//==============创建一个小堆=================
public void minHeap(Lists list){
int len=list.length();
int currentPos=(len-2)/2;
while(currentPos>=0){
filterDown(list, currentPos, len-1);
currentPos--;
}
}
public void filterDown(Lists list,int start,int end){
int i=start;
int j=2*i+1;
int temp=list.getValue(i);
while(j<=end){
if(j<end && list.getValue(j)>list.getValue(j+1))
j++;
if(temp<=list.getValue(j)){
break;
}else{
list.setValue(i, list.getValue(j));;
i=j;
j=2*i+1;
}
}
list.setValue(i, temp);
}
//===============增加节点====================
public void addNode(Lists list, int node){
list.insert(list.length(), node);
int end=list.length()-1;
filterUp(list,end);
}
public void filterUp(Lists list,int m){
int j=m;
int i=(j-1)/2;
int temp=list.getValue(j);
while(j>0){
if(list.getValue(i)<=temp)
break;
else{
list.setValue(j, list.getValue(i));
j=i;
i=(j-1)/2;
}
}
list.setValue(j, temp);
}
//==============删除一个节点,从根节点===============
public void deleteNode(Lists list){
list.setValue(0, list.getValue(list.length()-1));
list.countMinus();
int start=0;
int end=list.length()-1;
filterDown(list, start, end);
}
//===============进行堆排序======================
public void sortHeap(Lists list){
int len=list.length();
int temp=0;
for(int i=(len-2)/2;i>=0;i--)
filterDown(list, i, len-1);
for(int j=len-1;j>0;j--){
temp=list.getValue(0);
list.setValue(0, list.getValue(j));
list.setValue(j, temp);
filterDown(list, 0, j-1);
}
}
public static void main(String[] args) {
HeapSort sort=new HeapSort();
Lists list=new Lists();
int [] heap={35,26,48,10,59,64,17,23,45,31};
//初始化
for(int i=0;i<10;i++){
list.insert(i, heap[i]);
}
//创建小堆
sort.minHeap(list);
//增加一个节点
/*sort.addNode(list, 15);
System.out.println("小堆:");
for(int i=0;i<list.lengh();i++){
System.out.print(" "+list.getValue(i));
}*/
/*System.out.println("===========delete a node=======");
sort.deleteNode(list);*/
//==============从大到小排序=========
System.out.println("==========从大到小排序=========");
sort.sortHeap(list);
for(int i=0;i<list.length();i++){
System.out.print(" "+list.getValue(i));
}
}
}