diff --git a/general/src/algorithm/sorter.hpp b/general/src/algorithm/sorter.hpp index 9fdbae3..6461955 100644 --- a/general/src/algorithm/sorter.hpp +++ b/general/src/algorithm/sorter.hpp @@ -24,6 +24,18 @@ private: template class BSTNode { public: + BSTNode(){ + lchild = nullptr; + rchild = nullptr; + } + ~BSTNode(){ + if(nullptr != lchild){ + delete lchild; + } + if(nullptr != rchild){ + delete rchild; + } + }; T data; //每个结点的数据域包括关键字项和其他信息 struct BSTNode *lchild; struct BSTNode *rchild; @@ -62,33 +74,76 @@ int selectsort(T *data,uint64_t len,CompareHanlder handle){ data[i] = tmp; } } +template +void swap(T *a1,T *a2){ + T tmp = *a1; + *a1 = *a2; + *a2 = tmp; +} +template +void maxHeapIfy(T unsort[], int i,int n) //将i节点为根的堆中小的数依次上移,n表示堆中的数据个数 + +{ + int l = 2 * i + 1; //i的左儿子 + int r = 2 * i + 2; //i的右儿子 + int largest = i; //先设置父节点和子节点三个节点中最大值的位置为父节点下标 + if (l < n && unsort[l] > unsort[largest]) + largest = l; + if (r < n && unsort[r] > unsort[largest]) + largest = r; + if (largest != i) //最大值不是父节点,交换 + { + swap(&unsort[i],&unsort[largest]); + maxHeapIfy(unsort, largest, n); //递归调用,保证子树也是最大堆 + } +} template -void InsertBST(BSTNode &tree,T data) +void buildMaxHeap(T A[], int len) //建立最大堆 { - if(!tree){ //找到插入位置 - BSTNode *leaf = new BSTNode; //新节点保存数据 - leaf->data = data; - leaf->lchild = leaf->rchild = NULL; - tree = leaf; //把新结点放到已找到的插入位置 + std::cout <<"\r\n"; +// 从最后一个非叶子节点(n/2-1)开始自底向上构建, + for (int i = len / 2-1; i >= 0; i--) //从(n/2-1)调用一次maxHeapIfy就可以得到最大堆 + maxHeapIfy(A, i, len); + for (int i = 0; i < len; i++){ + std::cout << A[i]<<" "; } - else if(data < tree->data.key) - InsertBST(tree->lchild,data); - else if(data > tree->data.key) - InsertBST(tree->rchild,data); - else{ - cout<<"已有此值~"< +void adjust(T arr[], int len, int index) +{ + int left = 2*index + 1; + int right = 2*index + 2; + int maxIdx = index; + if(left arr[maxIdx]) + maxIdx = left; + if(right arr[maxIdx]) + maxIdx = right; // maxIdx是3个数中最大数的下标 + if(maxIdx != index) // 如果maxIdx的值有更新 + { + swap(arr[maxIdx], arr[index]); + adjust(arr, len, maxIdx); // 递归调整其他不满足堆性质的部分 + } + +} + + +template +void PreOrderTraverse(BSTNode *data) +{ + if (data) + { + cout << data->data << " "; + PreOrderTraverse(data->lchild); + PreOrderTraverse(data->rchild); } } template int heapsort(T *data,uint64_t len,CompareHanlder handle){ - for(uint32_t i=0; i