我建立了乙個heap的資料結構,而不是像stl那樣使用函式解決堆排序,當然stl的比較優雅一點,我只是提供第二個思路
#ifndef heap_sort_h
#define heap_sort_h
#include #include #include #ifdef _debug
#include #endif // _debug
template struct less
};//
// 最大堆,用於實現堆排序
// 演算法思路:
// 利用堆這種資料結構的特性,實現排序
// 在這裡的思路是heap含有乙個vec,並沒有事實能夠證明繼承比包含好用
//template , typename compare = less>
class maxheap
std::cout << std::endl;
// show the squence after build_max_heap()
for (std::vector::iterator iter = vec.begin();
iter != vec.end(); ++iter)
std::cout << std::endl;
#endif // _al_debug
} virtual ~maxheap()
inline size_type size() const
inline size_type capacity() const
inline const t& top() const
inline bool pop()
inline void push(const t& new_val)
protected:
container vec;
compare comp;
protected:
inline pos_type parent(pos_type i) const
inline pos_type right(pos_type i) const
inline pos_type left(pos_type i) const
inline bool has_left(pos_type i) const
inline bool has_right(pos_type i) const
inline bool has_parent(pos_type i) const
inline const t& value(pos_type i) const
inline const t& first() const
inline void swap(pos_type lhs, pos_type rhs)
// 建堆操作,時間複雜度:o(n)
void build_max_heap()
}} // 保持堆性質操作,時間複雜度:o(lgn)
void max_heapify(pos_type pos)
if (has_right(pos) && comp(value(max_pos), value(right_pos)))
#ifdef _al_debug
std::cout << std::endl;
#endif // _al_debug
if (max_pos != pos)
}void update_heapify(pos_type p)
std::cout << std::endl;
#endif // _al_debug
if (comp(value(parent_pos), value(cur)))
else break;
} }static const size_type _start_pos = 1;
};template void heap_sort(iterator first, iterator last)
//// 因為借助vector實現的,而不是自己利用allocator實現的,所以沒辦法控制
// heap-sort過程中將最大值放在末尾的步驟,所以只能將最大值賦給當前的指標
// 指向的位置
//template void _heap_sort_aux(iterator first, iterator last, val*)
}#endif
演算法導論堆排序實現
部分有序使用堆排序效率較高,基本有序使用插入排序或氣泡排序效率較高 include include 調整函式要求除了要調整的點,都要滿足堆的性質 void maxheapify int a,int i,int length else 取父節點 左右節點最大值 if right length 1 a ...
演算法導論 堆排序
堆排序演算法 heapsort max heapify過程,其執行時間為 lg n 是保持最大堆性質的關鍵 build max heap過程,以線性時間執行,可以在無序的輸入陣列基礎上構造出最大堆 heapsort過程,執行時間 n lg n 對乙個陣列原地進行排序 heapsort過程 1 建最大...
演算法導論 堆排序習題
1.怎樣利用最大 小 堆構成的優先實現先進先出佇列或者棧 開始看這道題沒有弄清以什麼優先,原來是先進先出佇列只要保證先進來優先順序高,棧保證後進來優先順序高,然後每次彈出堆頂元素即可 2.如何在logn時間裡刪除乙個元素 思路和如何在堆中增加乙個元素是一樣的,因為堆要的形狀要保證是一顆完全二叉樹,決...