堆排序
堆排序时间复杂度为nlgn,因为其用到了堆这种数据结构,而大根堆构造的子操作(从下到上调整堆)复杂度lgn,所以大根堆构造为lgn复杂度,排序过程中要N(输入数据规模大小)次对建好的大根堆进行从顶调整,所以整体也就为nlgn。证明过程算法导论上有详细证明。
以下是整个堆排序C程序:
extern int maxheapsize; /************************************************* Function: max_heapify Description: 将数组a中以pos为根的堆调整为大根堆,要保 证以左右孩子为根的堆是大根的 Input: Arg1: 要建大根堆的数组 Arg2: 根的位置 Return: void *************************************************/ void max_heapify(int a[], int pos) { int lpos, rpos; int buffer; lpos = find_left_child(pos); rpos = find_right_child(pos); //没有孩子节点到叶子节点时返回 if(lpos == -1) return; //当没有右孩子时 if(rpos == -1) { if(a[pos - 1] >= a[lpos - 1]) return; else { buffer = a[pos - 1]; a[pos - 1] = a[lpos - 1]; a[lpos - 1] = buffer; max_heapify(a, lpos); } } //左右孩子都有 else { //根最大 if (a[pos - 1] >= a[lpos - 1] && a[pos - 1] >= a[rpos - 1]) return; //左最大 else if (a[lpos - 1] >= a[rpos - 1]) { buffer = a[pos - 1]; a[pos - 1] = a[lpos - 1]; a[lpos - 1] = buffer; max_heapify(a, lpos); } //右最大 else { buffer = a[pos - 1]; a[pos - 1] = a[rpos - 1]; a[rpos - 1] = buffer; max_heapify(a, rpos); } } } /************************************************* Function: build_max_heap Description: 将数组a调整成一个大根堆 Input: Arg1: 要建大根堆的数组 Return: void *************************************************/ void build_max_heap(int a[]) { int startpos = maxheapsize >> 1; while (startpos != 0) { max_heapify(a, startpos); startpos --; } } /************************************************* Function: heap_sort Description: 用大根堆来进行堆排序 Input: Arg1: 大根堆 Return: void *************************************************/ void heap_sort(int a[]) { int size = maxheapsize; int buffer; //建立大根堆 build_max_heap(a); while (size != 0) { buffer = a[0]; a[0] = a[size - 1]; a[size - 1] = buffer; maxheapsize --; max_heapify(a, 1); size --; } } int find_left_child(int pos) { int leftchildpos; if(pos <= 0 || pos > maxheapsize) return -1; leftchildpos = pos << 1; if (leftchildpos > maxheapsize) return -1; else return leftchildpos; } int find_right_child(int pos) { int rightchildpos; if(pos <= 0 || pos > maxheapsize) return -1; rightchildpos = (pos << 1) + 1; if (rightchildpos > maxheapsize) return -1; else return rightchildpos; } int find_parent(int pos) { int parentpos; if(pos <= 0 || pos > maxheapsize) return -1; parentpos = pos >> 1; if (parentpos < 1) return -1; else return parentpos; } //===================main======== #include <stdlib.h> #include <stdio.h> int maxheapsize; void main() { int i; int max; printf("请您输入要建大根堆的数组大小\n"); scanf("%d", &maxheapsize); max = maxheapsize; int* heap = (int*)malloc(sizeof(int)*maxheapsize); printf("请您输入要建大根堆的数组内容\n"); for (i = 0; i != maxheapsize; i++) scanf("%d", heap + i); printf("建大根堆之前的数组为\n"); for (i = 0; i != maxheapsize; i++) printf("%d ", heap[i]); printf("\n"); heap_sort(heap); printf("堆排序后的数组为\n"); for (i = 0; i != max; i++) printf("%d ", heap[i]); printf("\n"); free(heap); }

浙公网安备 33010602011771号