堆排序

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++;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值