堆,是一個很有意思的資料結構。邏輯結構是樹,一般為二叉樹,每個節點的值都大于(小于)其子樹中的任意節點。也就是說,使用堆結構的數組 中,元素 是部分有序的。而正是這個特點,使得在堆上,得到最大值(最小值)的時間複雜度為O(1),移除最大值(最小值)、插入元素、改變元素值(或者是删除位置 已知的元素)的時間複雜度為O(lgn)。另外,用堆結構的排序是一種原地的、時間複雜度為O(nlgn)的排序算法。
可以參見動畫示範:示範
在優先級隊列前先說一下堆排序。
堆排序和歸并排序都是時間複雜度為O(nlgn)的排序算法,不同的是,歸并排序不是原地排序,它需要額外的n的空間;而堆排序是在原數組中進行的。
堆排序的過程,首先需要在給定的數組上進行建堆,然後在此基礎上一個一個的取根節點放到數組的後部,從後向前排。
建堆的過程BuildHeap 代碼很簡單,從下到上對每個節點依次處理,進行中調用了另一個方法:Heapify ,這個才是核心(具體參見完整代碼中的私有BuildHeap(void) 方法與Heapify(ItemType items[], int index, int count, bool isMaxHeap) 方法);Heapify 方法對指定節點的子樹進行堆化,具體地說,當除了根節點以外,其子樹中的所有節點都已經符合堆的要求時,Heapify 方 法會把指定的節點的子樹調整為一個堆,也就是把指定節點調整到子樹中合适的位置上,其時間複雜度為子樹的深度,O(lgn)。是以,可以算出建堆的時間複雜度為O(n),是線性的。這個時間複雜度怎麼得到的?n長度的樹,有lgn層,第h層(從0開始)至多有2^h的節點,進行一下求和就行了。
堆建好了,下來就是排序(具體可以見完整代碼中私有的SortTo(ItemType destitionArray[]) 方法)。因為堆的根節點是最值,是以隻需要依次把根節點和堆的最後一個元素交換位置,堆大小-1,再對根節點調用Heapify 就可以了。時間複雜度也就是n個Heapify ,O(nlgn)。
這樣進而得到總的排序時間複雜度O(nlgn)。
優先級隊列,目的是從隊列中取出的一個元素總是目前隊列中的最大值(最小值)。而堆剛好具有這個特點。當然,有序的ArrayList或者LinkedList也是可以的,但是慢,這個後面分析。
看一下優先級隊列都需要哪些操作。第一,其根本目的是能取出一個最值元素,這個就不用說了;第二,要能往隊列中插入元素。這是兩個核心的功能,另帶一些其他的輔助功能,如改變其中的某個元素的值,删除某個元素,得到其中的所有元素,得到其中元素個數等等。
給出優先級隊列的類的接口:
template
< typename ItemType >
class PriorityQueue {
PriorityQueue( bool isMaxHeap = true );
PriorityQueue( int size, bool isMaxHeap = true );
PriorityQueue(ItemType items[], int count, bool isMaxHeap = true );
int Count( void );
ItemType Get();
ItemType Remove();
void Insert(ItemType value);
void Change( int index, ItemType value);
ItemType Remove( int index);
bool ToArray(ItemType destinationArray[], int destinationSize);
~ PriorityQueue( void );
}
Remove() 方法是得到并移除第一個元素,Get() 僅僅是傳回第一個元素。這個優先級隊列用堆實作,進而可以得到主要方法Get() (O(1))、Remove() (O(lgn))、Insert() (O(lgn))較好的性能。具體實作參見完整代碼。
Heapify 方法書上給的是個遞歸的,我給改成疊代的了,避免函數調用帶來的些許開銷,進而可以提高一點内隐的時間與空間的性能。
那麼為什麼用堆實作優先級隊列比較合适呢?有序的線性表呢?
這個不難想,對于線性表,基于數組實作:首先,如果無序,要Get() 、要Remove() ,肯定要找到個最值,如果每次都去重新搜尋,就很慢了,而且數組牽扯到資料的整體移動(O(n));而保持有序,雖然Get() 、Remove() 快,但是Insert(ItemType value) 費的功夫有些多,因為堆中隻是部分有序,而數組需要保持整體有序,又是資料整體移動(O(n))。
基于連結清單的呢?連結清單的修改是很快,但連結清單如何快速搜尋與定位?建索引?-_-!
扯回來,說些關于具體實作時的問題。
當然,Change(int index, ItemType value) 與Remove(int index) 兩個方法在實際中是不實用的,或者是不現實的。因為通常情況下,不知道某個元素的index 是多少。通常要麼就不實作,要麼需要搜尋,或者有類似索引的機制。
還有,實際使用中隊列中存放的元素很可能是個什麼東西的指針,而不是一個沒什麼用的具體數值,這樣就還需要進行改進。
一種方式是原有的類不動,用一個實作了比較運算符的類或結構體的包裝類包裝一個有實際意義的東西,用這個類型當作PriorityQueue 的模闆參數。
或者是改造PriorityQueue ,把模闆參數ItemType 改成一個結構體或類,思想和上面的相似,不過這樣做功能會強大許多。比如添加一個這樣的内部類來替代模闆參數ItemType :
class QueueItem {
public :
QueueItem(ItemType theValue, int thePriority)
: priority(thePriority), value(theValue) {
}
// Getters and Setters
private :
friend PriorityQueue;
inline void SetOnwer(PriorityQueue * queue) {
onwer = queue;
}
inline void SetIndex( int index) {
this -> index = index;
}
inline int GetIndex() {
return index;
}
private :
PriorityQueue * onwer;
int index;
int priority;
ItemType value;
};
然後把原先代碼中,items 改為QueueItem 類型的數組;類内部的的ItemType 換成QueueItem 的指針。QueueItem 含有所在PriorityQueue 的index ,所有的地方注意改動這個;Insert 方法中new 一個QueueItem 來包裝ItemType ,并傳回此類的指針供外部更改使用(構造器就沒辦法了,可能無法保留帶有元素的構造方法);移除的方法中注意回收QueueItem 的空間;涉及到index 的接口可以改為傳入QueueItem 的指針,PriorityQueue 可直接根據QueueItem 指針指向的對象得到index;…… 細節比較瑣碎,不再描述,這個已經超出了本文的範圍。
完整的類代碼如下:
#include < exception >
#pragma once
using std::exception;
template
< typename ItemType >
class PriorityQueue {
private :
static const int DefaultSize = 10 ;
public :
PriorityQueue( bool isMaxHeap = true ) {
Initialize(nullptr, 0 , DefaultSize, isMaxHeap);
}
PriorityQueue( int size, bool isMaxHeap = true ) {
Initialize(nullptr, 0 , size, isMaxHeap);
}
PriorityQueue(ItemType items[], int count, bool isMaxHeap = true ) {
Initialize(items, count, count, isMaxHeap);
}
// Item count in queue.
inline int Count( void ) {
return count;
}
// Only get first item.
inline ItemType Get() {
if (count == 0 ) {
// empty queue.
// do something here.
throw exception();
} else {
return * items;
}
}
// Get and remove first item.
ItemType Remove() {
if (count == 0 ) {
// empty queue.
// do something here.
throw exception();
}
return Remove( 0 );
}
// Add a new item into queue.
void Insert(ItemType value) {
TryResize( true );
items[count - 1 ] = value;
TryMoveUp(count - 1 , value);
}
// Change value at index.
void Change( int index, ItemType value) {
if (index >= count) {
// out of range.
// throw exception or do nothing.
throw exception();
}
if (isMaxHeap ? value < items[index] : value > items[index]) {
TryMoveDown(index, value);
} else if (isMaxHeap ? value > items[index] : value < items[index]) {
TryMoveUp(index, value);
} else {
// do nothing.
}
}
ItemType Remove( int index) {
if (index >= count) {
// out of range.
// throw exception or do nothing.
throw exception();
}
ItemType result = items[index];
items[index] = items[count - 1 ];
TryResize( false );
if (index != count - 1 ) {
Heapify(items, index, count, isMaxHeap);
}
return result;
}
// Sort all items in queue to destinationArray, destinationSize for safe.
bool ToArray(ItemType destinationArray[], int destinationSize) {
if (destinationSize < count) {
// can not copy all items into destination array.
throw exception();
}
SortTo(destinationArray);
return true ;
}
~ PriorityQueue( void ) {
delete [] items;
}
private :
void Initialize(ItemType items[], int count, int size, bool isMaxHeap) {
if (size < count) {
// throw exception or set a new size.
size = count + DefaultSize;
}
this -> maxSize = size;
this -> count = count;
this -> isMaxHeap = isMaxHeap;
this -> items = new ItemType[size];
if (items != nullptr) {
for ( int i = 0 ; i < count; ++ i) {
this -> items[i] = items[i];
}
BuildHeap();
}
}
void BuildHeap( void ) {
for ( int i = ParentIndex(count - 1 ); i >= 0 ; -- i) {
Heapify(items, i, count, isMaxHeap);
}
}
// move items[index] down to the right position in its subtree.
void Heapify(ItemType items[], int index, int count, bool isMaxHeap) {
int currentIndex = index;
int targetIndex = index;
if (isMaxHeap) { // ... how to do this better?
while ( true ) {
int leftIndex = LeftChildIndex(currentIndex);
int rightIndex = RightChildIndex(currentIndex);
if (leftIndex < count && items[leftIndex] > items[targetIndex]) {
targetIndex = leftIndex;
}
if (rightIndex < count && items[rightIndex] > items[targetIndex]) {
targetIndex = rightIndex;
}
if (targetIndex != currentIndex) {
Swap(items + targetIndex, items + currentIndex);
currentIndex = targetIndex;
} else {
break ;
}
}
} else {
while ( true ) {
int leftIndex = LeftChildIndex(currentIndex);
int rightIndex = RightChildIndex(currentIndex);
if (leftIndex < count && items[leftIndex] < items[targetIndex]) {
targetIndex = leftIndex;
}
if (rightIndex < count && items[rightIndex] < items[targetIndex]) {
targetIndex = rightIndex;
}
if (targetIndex != currentIndex) {
Swap(items + targetIndex, items + currentIndex);
currentIndex = targetIndex;
} else {
break ;
}
}
}
}
inline int LeftChildIndex( int parentIndex) {
return RightChildIndex(parentIndex) - 1 ;
}
inline int RightChildIndex( int parentIndex) {
return ++ parentIndex << 1 ;
}
inline int ParentIndex( int index) {
return ( ++ index >> 1 ) - 1 ;
}
void SortTo(ItemType destitionArray[]) {
// copy items.
for ( int i = 0 ; i < count; ++ i) {
destitionArray[i] = items[i];
}
// only for exercises... do heap sort in destitionArray.
for ( int i = count, tempCount = count; i > 0 ; -- i) {
Swap(destitionArray, destitionArray + tempCount - 1 );
-- tempCount;
Heapify(destitionArray, 0 , tempCount, isMaxHeap);
}
}
void Swap(ItemType * a, ItemType * b) {
ItemType temp = * a;
* a = * b;
* b = temp;
}
void TryMoveUp( int index, ItemType value) {
if (isMaxHeap ? value < items[index] : value > items[index]) {
// do something about value error.
throw exception();
}
items[index] = value;
int currentIndex = index;
int parentIndex = ParentIndex(index);
while (index > 0 && (isMaxHeap ? items[parentIndex] < items[index] : items[parentIndex] > items[index])) {
Swap(items + index, items + parentIndex);
index = parentIndex;
parentIndex = ParentIndex(parentIndex);
}
}
void TryMoveDown( int index, ItemType value) {
if (isMaxHeap ? value > items[index] : value < items[index]) {
// do something about value error.
throw exception();
}
items[index] = value;
Heapify(items, index, count, isMaxHeap);
}
void TryResize( bool isIncrease) {
if (isIncrease) {
if (count >= maxSize) {
maxSize = (maxSize << 1 ) + 10 ;
NewItems(maxSize);
}
++ count;
} else {
if (count < maxSize >> 1 ) {
maxSize = (maxSize >> 1 ) + 5 ;
NewItems(maxSize);
}
-- count;
}
}
void NewItems( int size) {
ItemType * newItems = new ItemType[size];
// copy items.
for ( int i = 0 ; i < count; ++ i) {
newItems[i] = items[i];
}
delete [] items;
items = newItems;
}
private :
ItemType * items;
int count;
int maxSize;
bool isMaxHeap;
};
原文來自:
http://blogold.chinaunix.net/u3/104216/showart_2090365.html
轉載于:https://www.cnblogs.com/avril/archive/2011/05/04/2036918.html