c.代码3(交换)
void Swap(DateType*p1, DateType*p2)
{DateType tmp = *p1;*p1 = *p2;*p2 = tmp;
}
2.建堆
void CreatHeap(Heap*p,DateType*num,int n)
{assert(p);p->a = (DateType*)malloc(n * sizeof(DateType));if (p->a == NULL){printf("malloc failed\n");exit(-1);}memcpy(p->a, num, n * sizeof(DateType));p->size = n;p->capacity = n;//建小堆for (int i = (n - 1 - 1) / 2; i >= 0; i--){AdjustDown(p->a, p->size, i);}
}
3.插入数据
void HeapPush(Heap*p, DateType x)
{assert(p);if (p->size == p->capacity){DateType*tmp = (DateType*)realloc(p->a, (p->capacity) * 2 * sizeof(DateType));if (tmp == NULL){printf("realloc failed\n ");exit(-1);}}(p->capacity) *= 2;p->a[p->size] = x;++(p->size);//向上调整AdjustUp(p->a, p->size-1);
}
4. 删除数据
void HeapPop(Heap*p, DateType x)
{assert(p);Swap(&p->a[0], &p->a[p->size-1]);--(p->size);AdjustDown(p->a, p->size, 0);//左右子树还是小堆,直接调整行了
}
把堆顶的数据与最后一个数据交换,再次调整size-1个数据。
5.获取堆顶的数据
DateType HeapTop(Heap*p)
{assert(p);return p->a[0];
}
6.堆的数据个数
int HeapSize(Heap*p)
{assert(p);return p->size;
}
7.判空
bool HeapIsEmpty(Heap*p)
{assert(p);return p->size == 0;
}
8.打印
void Print(Heap*p)
{assert(p);for (int i = 0; i size; i++){printf("%d ", (p->a)[i]);}printf("\n");int count = 0;//计数int levelsize = 1;for (int i = 0; i size; i++){printf("%d ", p->a[i]);++count;if (count == levelsize){printf("\n");levelsize *= 2;count = 0;//重新计数}}printf("\n");
}
8.销毁
void HeapDestory(Heap*p)
{assert(p);free(p->a);p->a = NULL;p->capacity = p->size = 0;
}
9.测试
int main()
{int num[] = { 12,15,17,23,10,25 };int n = sizeof(num) / sizeof(num[0]);Heap a;//创建小堆CreatHeap(&a,num, n);Print(&a);printf("\n");//插入数据HeapPush(&a, 1);Print(&a);//删除对顶的数据HeapPop(&a);Print(&a);printf("\n");//获取堆顶数据int ret=HeapTop(&a);printf("The top date is %d\n",ret);//堆的数据个数int number=HeapSize(&a);printf("The number of heap is %d\n", number);//销毁HeapDestory(&a);return 0;
}
10.测试结果
11.用堆排序(降序)
a.代码1
int main()
{DateType num[] = { 12,15,17,23,10,25 };int n = sizeof(num) / sizeof(num[0]);HeapSort(num, n);for (int i = 0; i }
void HeapSort(int*num, int n)
{//建小堆for (int i = (n - 1 - 1) / 2; i >= 0; i--){AdjustDown(num, n, i);}int end = n - 1;while (end>0){Swap(&num[0], &num[end]);AdjustDown(num, end, 0);--end;}
}
运行结果
堆的基本操作今天就分享在到这里了,谢谢你的浏览,如果对你有帮助的话,可以点一个赞,随便来个关注。