自己动手实现使用最小堆解决Topk问题

package extend;

public class MyMinHeap {
private int[]data;//存放数据
public MyMinHeap(int []data)
{
	this.data=data;
	this.buildMyMinHeap();
}
@Override
public String toString() {
	// TODO Auto-generated method stub
	StringBuilder sb=new StringBuilder();
	for(int i=0;i=0;i--)
	{
		heapfy(i);
	}
}
public int[] getData() {
	return data;
}
public void setData(int[] data) {
	this.data = data;
}
public int getRoot()
{
	return this.data[0];//获取根元素
}
private void heapfy(int i)
{
	
	int left=this.getLeft(i);
	int right=this.getRight(i);
	int smallest=i;//用来记录最小的元素下标
	//System.out.println("i:"+i+",left:"+left+",right:"+right+",smallest:"+this.data[smallest]+",left:"+this.data[left]+",length:"+this.data.length);
	
	//***********下列操作仅是为了求出最小的结点,并将父节点与该节点交换******************
	if((leftdata[left]))
	{
		//System.out.println("letf");
		smallest=left;
	}
	if(rightthis.data[right])
	{
		//System.out.println("right");
		smallest=right;
	}
	//System.out.println("i:"+i+",s:"+smallest);
	if(i==smallest)//说明左右孩子结点均大于该节点 则不需要进行下面的操作
		return;
	//System.out.println("交换:"+data[i]+","+data[smallest]);
    swap(i,smallest);
    heapfy(smallest);//只对受影响的进行重排
		
}
private void swap(int i,int j)
{
	int temp=this.data[i];
	this.data[i]=this.data[j];
	this.data[j]=temp;
}
private int getLeft(int i)//获取左孩子结点的下标
{
	return (2*i+1);
}
private int getRight(int i)//获取右孩子结点的下标
{
	return (2*i+2);
}
public void setRoot(int data)
{
	this.data[0]=data;
	this.heapfy(0);
}
public static void main(String[] args) {
	int []data={9,8,7,6,5,1000,3,2,1};
	MyMinHeap heap=new MyMinHeap(data);
	System.out.println(heap);
}
}

package dataStructer;

import extend.MyMinHeap;

public class MyTopK {
private int topKNum;
private int []data;
private int []temp;
public MyTopK(int topKNum,int []data)
{
	temp=new int[topKNum];
	this.data=data;
	for(int i=0;iheap.getRoot())
		{
			heap.setRoot(data[j]);
		}
	}
}
public int[]getTopK()
{
	return temp;
}
public static void main(String[] args) {
        int []data={1,2,35,5343,4,5,6,7,8,9};
        MyTopK topk=new MyTopK(3,data);
        int []topkData=topk.getTopK();
        for(int i=0;i

你可能感兴趣的:(算法)