import java.util.Arrays;
import java.util.PriorityQueue;
public class FirstQueue {
private static int[] array;
private static int size;
public FirstQueue() {
// 隊列初始長度爲32
array = new int[32];
}
private void enQueue(int key) {
// 隊列長度超出範圍,擴容
if (size >= array.length) {
resize();
}
array[size++] = key;
}
private int deQueue() throws Exception {
if (size <= 0) {
throw new Exception("這個隊列是空的!");
}
// 獲取堆頂元素
int head = array[0];
// 讓最後一個元素移動到堆頂
array[0] = array[--size];
downAdjust();
return head;
}
/**
* 上浮調整
*
* @param array 待調整的堆
*/
private static void upAdjust(int[] array) {
int childIndex = array.length - 1;
int parentIndex = (childIndex - 1) / 2;
// temp保存插入的葉子節點值,用於最後的賦值
int temp = array[childIndex];
while (childIndex > 0 && temp < array[parentIndex]) {
// 無需真正交換,單向賦值即可
array[childIndex] = array[parentIndex];
childIndex = parentIndex;
parentIndex = (parentIndex - 1) / 2;
}
// 最後將值給它
array[childIndex] = temp;
}
/**
* 下沉調整
*
* @param array 待調整的堆
* @param parentIndex 要下沉的父節點
* @param lenght 堆得有效大小
*/
private static void downAdjust() {
// temp保存父節點值,用於最後賦值
int parentIndex = 0;
int temp = array[parentIndex];
int childIndex = 1;
// 左孩子
while (childIndex < size) {
// 如果有右孩子,且右孩子小於左孩子的值,則定位到右孩子
if (childIndex + 1 < size && array[childIndex] + 1 > array[childIndex]) {
childIndex++;
}
// 如果父節點則任何一個孩子的值,則直接跳出
if (temp >= array[childIndex]) {
break;
}
// 無需真正交換,單向賦值即可
array[parentIndex] = array[childIndex];
parentIndex = childIndex;
childIndex = 2 * childIndex + 1;
}
array[parentIndex] = temp;
}
private void resize() {
// 隊列容量翻倍
int newSize = this.size = 2;
this.array = Arrays.copyOf(this.array, newSize);
}
// 測試
public static void main(String[] args) throws Exception {
FirstQueue firstQueue = new FirstQueue();
firstQueue.enQueue(3);
firstQueue.enQueue(5);
firstQueue.enQueue(10);
firstQueue.enQueue(2);
firstQueue.enQueue(7);
System.out.println("出隊元素: "+firstQueue.deQueue());
System.out.println("出隊元素: "+firstQueue.deQueue());
}
}
二叉堆之優先隊列的實現
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.