您好,登錄后才能下訂單哦!
本篇內(nèi)容主要講解“如何用Java實(shí)現(xiàn)小頂堆和大頂堆”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實(shí)用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“如何用Java實(shí)現(xiàn)小頂堆和大頂堆”吧!
每個結(jié)點(diǎn)的值都大于或等于其左右孩子結(jié)點(diǎn)的值
每個結(jié)點(diǎn)的值都小于或等于其左右孩子結(jié)點(diǎn)的值
public class HeapNode{ private int size;//堆大小 private int[] heap;//保存堆數(shù)組 //初始化堆 public HeapNode(int n) { heap = new int[n]; size = 0; } //小頂堆建堆 public void minInsert(int key){ int i = this.size; if (i==0) heap[0] = key; else { while (i>0 && heap[i/2]>key){ heap[i] = heap[i/2]; i = i/2; } heap[i] = key; } this.size++; } //大頂堆建堆 public void maxInsert(int key){ int i = this.size; if (i==0) heap[0] = key; else { while (i>0 && heap[i/2]<key){ heap[i] = heap[i/2]; i = i/2; } heap[i] = key; } this.size++; } //小頂堆刪除 public int minDelete(){ if (this.size==0) return -1; int top = heap[0]; int last = heap[this.size-1]; heap[0] = last; this.size--; //堆化 minHeapify(0); return top; } //大頂堆刪除 public int maxDelete(){ if (this.size==0) return -1; int top = heap[0]; int last = heap[this.size-1]; heap[0] = last; this.size--; //堆化 maxHeapify(0); return top; } //小頂堆化 public void minHeapify(int i){ int L = 2*i,R=2*i+1,min; if (L<=size && heap[L] < heap[i]) min = L; else min = i; if (R <= size && heap[R] < heap[min]) min = R; if (min!=i){ int t = heap[min]; heap[min] = heap[i]; heap[i] = t; minHeapify(min); } } //大頂堆化 public void maxHeapify(int i){ int L = 2*i,R=2*i+1,max; if (L<=size && heap[L] > heap[i]) max = L; else max = i; if (R <= size && heap[R] > heap[max]) max = R; if (max!=i){ int t = heap[max]; heap[max] = heap[i]; heap[i] = t; maxHeapify(max); } } //輸出堆 public void print(){ for (int i = 0; i < this.size; i++) { System.out.print(heap[i]+" "); } System.out.println(); } }
public class Heap { static int[] a = {5,3,6,4,2,1}; static int n = a.length; public static void main(String[] args){ HeapNode heapNode = new HeapNode(n); for (int i = 0; i < n; i++) { heapNode.maxInsert(a[i]); } heapNode.print(); for (int i = 0; i < n; i++) { int min = heapNode.maxDelete(); System.out.print("堆頂:"+min+" 剩下堆元素:"); heapNode.print(); } } }
到此,相信大家對“如何用Java實(shí)現(xiàn)小頂堆和大頂堆”有了更深的了解,不妨來實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。