優先佇列主要用來處理部分有序的問題,例如n個元素抽取m個最小元素,堆是可以處理有限佇列的一種方式,需要注意的是堆有序不等同於資料有序。二叉堆可以保證每個節點的資料都大於或者小於他的子節點,前者叫做最大堆,後者叫做最小堆,可以分別處理抽取出最小值和最大值的問題。以最大堆為例,如果要從m個資料中抽取n個最小的,每次新資料和堆頂最大值進行交換,然後採用下沉的方式保證堆有序,可以獲取n個最小值。最大堆實現如下:
,同時堆排序可以看做一種選擇排序,複雜度略高於快速排序,實現如下:public class maxpqwhere t : icomparable
/// /// 返回最大元素
///
///
public t delmax()
public void test()
console.readkey();
}/// /// 比較
///
///
///
///
bool less(int a, int b)
/// /// 交換
///
///
///
void exch(int i, int j)
/// /// 由下至上的上浮
///
public void swim(int k)
}/// /// 由上至下的下潛
///
public void sink(int k)
exch(j, k);
k = j;}}
}
class sort_heapwhere t: icomparable
count = 0;
}public bool isempty()
public int size()
///
/// 新增乙個元素
///
///
public void insert(t v)
else
swim(count);
}///
/// 返回最大元素
///
///
public t delmax()
public void test()
console.readkey();
}///
/// 比較
///
///
///
///
bool less(int a, int b)
///
/// 由下至上的上浮
///
public void swim(int k)
}///
/// 由上至下的下潛
///
public void sink_sort(int k)
else if (less(k, j))
else
}else}}
///
/// 由上至下的下潛
///
public void sink(int k , int n)
exch(j, k);
k = j;}}
///
/// 堆排序,最大堆,非遞增排序,如需改為遞減修改less函式即可
///
public void sort(listv)
while (n > 1)}}
C primer(第四版)讀書筆記5
extern int i declares but does not define i int i declares and defines i extern宣告不是定義,也不分配儲存空間。事實上,它只是說明變數定義在程式的其他地方。程式中變數可以宣告多次,但只能定義一次。如果宣告有初始化式,那麼它...
C primer(第四版)讀書筆記2
以下幾種情況都可能引發執行時或編譯時錯誤 1 delete不是new分配的空間 2 重複delete new分配的空間兩次以上 3 在釋放動態陣列時忘了方括號對 inti int pi i delete pi vs 2008 會執行時錯誤 string str dwarves delete str ...
C Primer中文版第四版 讀書筆記
2011.8.10 p46 只有當extern 宣告位於函式外部時,才可以含有初始化式。extern double pi 3.1416 pi 是乙個全域性變數,這是乙個定義 p50 在全域性作用域宣告的const 變數是定義該物件的檔案的區域性變數 僅作用在該檔案中 要使 const 變數能夠在其他...