package cn.ccnu.lzc;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;
public class heapSort {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
int size,j;
System.out.println("enter number of items");
size=getInt();
heap theHeap=new heap(size);
for(j=0;j<size;j++){
int random=new Random().nextInt(100);
Node newNode=new Node(random);
theHeap.insertAt(j, newNode);
theHeap.incrementSize();
}
System.out.print("Random Array: ");
theHeap.displayArray();
//建堆
for(j=size/2-1;j>=0;j--){
theHeap.trickleDown(j);
}
System.out.print("Heap: ");
theHeap.displayArray();
for(j=size-1;j>0;j--){
Node biggestNode=theHeap.remove();
theHeap.insertAt(j, biggestNode);
}
System.out.print("Sort: ");
theHeap.displayArray();
}
private static int getInt() throws Exception {
// TODO Auto-generated method stub
String s=getString();
return Integer.parseInt(s);
}
private static String getString() throws Exception {
// TODO Auto-generated method stub
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
String s=br.readLine();
return s;
}
}
class Node{
private int iData;
public Node(int key){
this.iData=key;
}
public int getKey(){
return iData;
}
}
class heap{
private Node[] heapArray;
private int maxSize; //size of array
private int currentSize; //number of items in array
public heap(int maxSize){
this.maxSize=maxSize;
heapArray=new Node[maxSize];
currentSize=0;
}
public Node remove()//delete item with max key
{
if(currentSize==0)
return null;
Node root=heapArray[0];
heapArray[0]=heapArray[--currentSize];
trickleDown(0);
return root;
}
//向下构建堆
public void trickleDown(int index){
int largerChild;
Node top=heapArray[index];
while(index<currentSize/2){
int leftChild=2*index+1;
int rightChild=2*index+2;
if(rightChild<currentSize&&heapArray[rightChild].getKey()>heapArray[leftChild].getKey())
largerChild=rightChild;
else
largerChild=leftChild;
if(top.getKey()>=heapArray[largerChild].getKey())
break;
heapArray[index]=heapArray[largerChild];
index=largerChild;
}
heapArray[index]=top;
}
public void displayArray(){
for(Node i:heapArray){
System.out.print(i.getKey()+" ");
}
System.out.println();
}
public void insertAt(int index,Node newNode){
heapArray[index]=newNode;
}
public void incrementSize(){
currentSize++;
}
}
堆排序
最新推荐文章于 2024-09-04 23:05:17 发布