堆排序C语言实现

来源:互联网 发布:最简单的php爬虫 编辑:程序博客网 时间:2024/06/11 10:11
/* ============================================================================ Name        : headSort.c Author      : 董乐强 Version     : Copyright   : Your copyright notice Description : Hello World in C, Ansi-style ============================================================================ *//** * 堆排序就是优先队列,这个在实际运用很多,例如在线程池中有多个线程等待cpu,每个线程都有个优先级,当新进来的一个 * 线程的时候,那么需要从新对线程池更新,随的优先级高,则拥有cpu的权限最高。 */#include <stdio.h>#include <stdlib.h>#include <time.h>typedef int ElemType;//用于交换两个元素void swap(ElemType * a, ElemType * b) {ElemType temp = 0;temp = *a;*a = *b;*b = temp;}//当前节点向下调整,建立最小堆void shifDown(int i, ElemType * p, int n) {int t = 1; //用于记录堆中最小节点的位置int flag = 0; //用于标记是否要进行堆的调整//如果flag=0且 堆中至少必须存在左孩子while (flag == 0 && i * 2 <= n) {//将左孩子与当前的节点进行比较if (p[i] > p[i * 2])t = i * 2;elset = i;//将右孩子与当前堆中的最小节点进行比较(前提是右孩子必须存在)if ((i * 2 + 1) <= n)if (p[t] > p[i * 2 + 1])t = i * 2 + 1;//i节点需要调整if (i != t) {swap(&p[i], &p[t]);i = t;} elseflag = 1;}}//当前节点向上调整,建立最小堆void shifUp(int i, ElemType * p) {int t = i; //用于记录最小值节点的位置int flag = 0; // 用于记录是否需要调整while (flag == 0 && i != 1) {if (p[i] < p[i / 2])t = i / 2;elset = i;if (t != i) {swap(&p[i], &p[t]);i = t;} elseflag = 1;}}//建堆void create(ElemType *p, int n) {int i = 1;for (i = n / 2; i >= 1; i--)shifDown(i, p, n);}//堆排序void headSort(ElemType * p, int n) {int position = n;//建堆create(p, n);while (position != 1) {//堆顶元素与堆中最后一个叶子节点进行交换swap(&p[1], &p[position]);position--;//从新调整为最小堆shifDown(1, p, position);}}int main(void) {puts("排序"); /* prints 排序 */ElemType data[10];int i = 0;srand(time(NULL));for (i = 1; i < 10; i++)data[i] = rand() % 10000 / 100;//排序前printf("---------排序前---------------");for (i = 1; i < 10; i++)printf("%d ", data[i]);printf("\n");headSort(data, 9);printf("---------排序后----------------");for (i = 1; i < 10; i++)printf("%d ", data[i]);printf("\n");return EXIT_SUCCESS;}

原创粉丝点击