最小堆,最大堆
最小堆
package com.tools; public class MinHeap { public int[] num; public MinHeap(int[] num){ this.num = num; build(); } //交换数据 private void swap(int i , int j){ int temp; temp = num[i]; num[i] = num[j]; num[j] = temp; } //初始化构造二叉堆 private void build(){ for(int i = 0 ; i <= num.length/2-1; i++){ Heap(i); } } //对堆进行整理 private void Heap(int index){ int small = index; int left,right; left = (index+1)*2-1; right = (index+1)*2; if(left<num.length&&num[left]<num[index]) small = left; if(right<num.length&&num[right]<num[small]) small = right; if(small == index) return; swap(small, index); Heap(small); } public int GetRoot(){ return num[0]; } public void SetHeadValue(int value){ num[0] = value; Heap(0); } }
最大堆
package com.tools; public class MaxHeap { public int[] num; public MaxHeap(int[] num){ this.num = num; BuildHeap(); } private void BuildHeap(){ for(int i = num.length/2-1 ; i >=0 ;i--){ Heap(i); } } private void swap(int i, int j){ int temp; temp = num[i]; num[i] = num[j]; num[j] = temp; } //index = 2 private void Heap(int index){ int left,right; left = (index+1)*2-1; right = (index+1)*2; int max = index; if(left<num.length && num[left]>num[index]) max = left; if(right<num.length && num[right]>num[max]) max = right; if(index == max) return ; swap(max,index); Heap(max); } public int GetRoot(){ return num[0]; } public void SetHeadValue(int value) { num[0] = value; Heap(0); } }
实现类
package com.algorithm05; import java.util.Scanner; import com.tools.MaxHeap; import com.tools.MinHeap; public class Algorithm40 { public static void main(String[] args) { int[] num = new int[]{5,2,1,4,8,12,3,100,2000,30,50}; Scanner scanner = new Scanner(System.in); int k; k = scanner.nextInt(); int[] topK = new int[k]; //首先将数组中前k个数放入topk数组中。 for(int i = 0 ; i < k ; i++){ topK[i] = num[i]; } //将topk数组转换为最小堆 MinHeap minHeap = new MinHeap(topK); //前k个数据进入topk数组中,之后对数组中剩余数组进行最小堆的匹配 for(int j = k ; j < num.length; j++){ //如果数组中的值比topk最小的值还要小,则对其进行更换。并更新topk的数组的结构 if(num[j]>minHeap.num[0]) { minHeap.SetHeadValue(num[j]); } } ////前k个数据进入topk数组中,之后对数组中剩余数组进行最大堆的匹配 MaxHeap maxHeap = new MaxHeap(topK); for(int j = k ; j < num.length ; j++){ if(num[j]<maxHeap.num[0]) { maxHeap.SetHeadValue(num[j]); } } } }