java-5.查找最小的K个元素-使用最大堆

[code="java"]
import java.util.Arrays;
import java.util.Random;


public class MinKElement {

/**
* 5.最小的K个元素
* I would like to use MaxHeap.
* using QuickSort is also OK
*/
public static void main(String[] args) {
MinKElement mke=new MinKElement();
int[] a={1,2,3,4,5,6,7,8};
int k=4;
mke.disArrange(a);
System.out.println("after disarranging,the array a[]="+Arrays.toString(a));
mke.findKMin(a,k);

}

//rearrange the array.just for test.
public void disArrange(int[] a){
for(int i=0,len=a.length;i<len;i++){
Random random=new Random();
int j=random.nextInt(len);
swap(a,i,j);
}
}
public void findKMin(int[] a,int k){
int[] heap=a;//you can do this:int[] heap=new int[k].but that maybe space-cost

//create MaxHeap of K elements.from the lastRootIndex to 0.
int rootIndex=k/2-1;
while(rootIndex>=0){
reheap(heap,rootIndex,k-1);
rootIndex--;
}
for(int i=k,len=heap.length;i<len;i++){
if(heap[i]<heap[0]){
heap[0]=heap[i];
reheap(heap,0,k-1);
}
}
System.out.print("the K min elements=");
for(int i=0;i<k;i++){
System.out.print(heap[i]+",");
}
}

//reheap:from root to lastIndex.
public void reheap(int[] heap,int rootIndex,int lastIndex){
int orphan=heap[rootIndex];
boolean done=false;
int leftIndex=rootIndex*2+1;
while(!done&&leftIndex<=lastIndex){
int largerIndex=leftIndex;
if(leftIndex+1<=lastIndex){
int rightIndex=leftIndex+1;
if(heap[rightIndex]>heap[leftIndex]){
largerIndex=rightIndex;
}
}
//Attention! should not use -->heap<heap[largerIndex]<--.
//I spend time to find the problem....
if(orphan<heap[largerIndex]){
heap[rootIndex]=heap[largerIndex];
rootIndex=largerIndex;
leftIndex=rootIndex*2+1;
}else{
done=true;
}
}
heap[rootIndex]=orphan;

}
public void swap(int[] a,int i,int j){
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}

[/code]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值