测试排序算法

master
a7458969 2020-05-11 01:44:10 +08:00
parent 06dcb18dcb
commit c27a7d85cd
1 changed files with 74 additions and 19 deletions

View File

@ -24,6 +24,18 @@ private:
template <typename T> template <typename T>
class BSTNode { class BSTNode {
public: public:
BSTNode<T>(){
lchild = nullptr;
rchild = nullptr;
}
~BSTNode<T>(){
if(nullptr != lchild){
delete lchild;
}
if(nullptr != rchild){
delete rchild;
}
};
T data; //每个结点的数据域包括关键字项和其他信息 T data; //每个结点的数据域包括关键字项和其他信息
struct BSTNode *lchild; struct BSTNode *lchild;
struct BSTNode *rchild; struct BSTNode *rchild;
@ -62,33 +74,76 @@ int selectsort(T *data,uint64_t len,CompareHanlder<T> handle){
data[i] = tmp; data[i] = tmp;
} }
} }
template <typename T>
void swap(T *a1,T *a2){
T tmp = *a1;
*a1 = *a2;
*a2 = tmp;
}
template <typename T>
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 <typename T> template <typename T>
void InsertBST(BSTNode<T> &tree,T data) void buildMaxHeap(T A[], int len) //建立最大堆
{ {
if(!tree){ //找到插入位置 std::cout <<"\r\n";
BSTNode<T> *leaf = new BSTNode<T>; //新节点保存数据 // 从最后一个非叶子节点n/2-1开始自底向上构建
leaf->data = data; for (int i = len / 2-1; i >= 0; i--) //从n/2-1调用一次maxHeapIfy就可以得到最大堆
leaf->lchild = leaf->rchild = NULL; maxHeapIfy(A, i, len);
tree = leaf; //把新结点放到已找到的插入位置 for (int i = 0; i < len; i++){
std::cout << A[i]<<" ";
} }
else if(data < tree->data.key) std::cout <<"\r\n";
InsertBST(tree->lchild,data); }
else if(data > tree->data.key) template <typename T>
InsertBST(tree->rchild,data); void adjust(T arr[], int len, int index)
else{ {
cout<<"已有此值~"<<endl; int left = 2*index + 1;
return; int right = 2*index + 2;
int maxIdx = index;
if(left<len && arr[left] > arr[maxIdx])
maxIdx = left;
if(right<len && arr[right] > arr[maxIdx])
maxIdx = right; // maxIdx是3个数中最大数的下标
if(maxIdx != index) // 如果maxIdx的值有更新
{
swap(arr[maxIdx], arr[index]);
adjust(arr, len, maxIdx); // 递归调整其他不满足堆性质的部分
}
}
template <typename T>
void PreOrderTraverse(BSTNode<T> *data)
{
if (data)
{
cout << data->data << " ";
PreOrderTraverse(data->lchild);
PreOrderTraverse(data->rchild);
} }
} }
template <typename T> template <typename T>
int heapsort(T *data,uint64_t len,CompareHanlder<T> handle){ int heapsort(T *data,uint64_t len,CompareHanlder<T> handle){
for(uint32_t i=0; i <len; i++) buildMaxHeap(data, len); //先建立堆
{
printf("%d ", data[i]);
// 先组二叉排序数
heapinert(data[i]);
}
} }
#endif //GENERAL_SORTER_H #endif //GENERAL_SORTER_H