寫得很不效率,這個東西.很多細節,似乎每次寫,都要重新發現.寫出來了,就好啊.
//binaryHeap.cpp -- 2011-08-28-23.06//Purpose://Define methods of class "binaryHeap".#include "stdafx.h"#include "binaryHeap.h"//Private methods://---------------------void binaryHeap ::m_percolateUp (int index){Node temp = m_heap[index] ;size_t i = index ;size_t parent = (i - 1) / 2 ;while (i != 0){if (temp.weight < m_heap[parent].weight){m_heap[i] = m_heap[parent] ;i = parent ;parent = (i - 1) / 2 ;}else{m_heap[i] = temp ;break ;}}if (0 == i){m_heap[0] = temp ;}}//---------------------//---------------------void binaryHeap ::m_percolateDown (int index){Node temp = m_heap[index] ;int i = index ;int child = i * 2 + 1 ;while (child < m_currentSize){if (child != m_currentSize - 1 && m_heap[child + 1].weight < m_heap[child].weight)++child ;if (temp.weight > m_heap[child].weight){m_heap[i] = m_heap[child] ;i = child ;child = i * 2 + 1 ;}else{m_heap[i] = temp ;break ;}}if (child >= m_currentSize){m_heap[i] = temp ;}}//---------------------//Public methods://---------------------binaryHeap ::binaryHeap (int size){if (size <= 0){std ::cerr << "Wrong size." << std ::endl ;return ;}m_heap = new Node[size] ;if (NULL == m_heap){std ::cerr << "Out of space." << std ::endl ;return ;}m_size = size ;m_currentSize = 0 ;}//---------------------//---------------------binaryHeap ::~binaryHeap (void){delete []m_heap ;}//---------------------//---------------------bool binaryHeap ::isEmpty (void){if (0 == m_currentSize)return true ;elsereturn false ;}//---------------------//---------------------bool binaryHeap ::isFull (void){if (m_currentSize == m_size)return true ;elsereturn false ;}//---------------------//---------------------bool binaryHeap ::insert (int startIndex, int endIndex, int weight){if (isFull()){std ::cerr << "Heap is full already." << std ::endl ;return false ;}if (startIndex >= m_size || startIndex < 0 ||endIndex >= m_size || endIndex < 0){std ::cerr << "Wrong start index or end index." << std ::endl ;return false ;}m_heap[m_currentSize].startIndex = startIndex ;m_heap[m_currentSize].endIndex = endIndex ;m_heap[m_currentSize].weight = weight ;m_percolateUp(m_currentSize) ;++m_currentSize ;return true ;}//---------------------//---------------------bool binaryHeap ::deleteMin (Node * const pNode){if (isEmpty()){std ::cerr << "Heap is empty already." << std ::endl ;return false ;}*pNode = m_heap[0] ;m_heap[0] = m_heap[--m_currentSize] ;m_percolateDown(0) ;return true ;}//---------------------