数据结构基础7.3:堆排序

来源:互联网 发布:json解析哪些框架 编辑:程序博客网 时间:2024/06/01 14:07

一.定义:

堆排序是利用堆的性质进行的一种选择排序。

二.算法描述:

1. 将初始待排序关键字序列(R1,R2....Rn)构建成大顶堆,此堆为初始的无序区。

2. 将堆顶元素R[1]与最后一个元素R[n]交换,此时得到新的无序区(R1,R2,......Rn-1)和新的有序区(Rn),且满足R[1,2...n-1]<=R[n]。

3 .由于交换后新的堆顶R[1]可能违反堆的性质,因此需要对当前无序区(R1,R2,......Rn-1)调整为新堆,然后再次将R[1]与无序区最后一个元素交换,得到新的无序(R1,R2....Rn-

2)和新的有序区(Rn-1,Rn)。不断重复此过程直到有序区的元素个数为n-1,则整个排序过程完成。

三.代码实现:

#include <stdio.h>#include <stdlib.h>#include <iostream>using namespace std;#define ERROR 1#define OK 0;typedef int Status;typedef struct heap {    int* pArray;    int size;} *maxheap;/* 以n为结点不是堆,左子树是堆,右子树是堆,调整为一个堆,方法是向下过滤 */Status PercDown(maxheap mh, int n){    int parent, child, temp;        if(!mh)        return ERROR;    if(mh->size <= 1)        return OK;        temp = mh->pArray[n];    parent = n;        for(child = n * 2 + 1; child <= mh->size - 1; child = parent * 2 + 1) {        if(child != mh->size - 1 && mh->pArray[child] < mh->pArray[child + 1])            child++;        if(temp < mh->pArray[child]) {            mh->pArray[parent] = mh->pArray[child];            parent = child;        }        else            break;    }    mh->pArray[parent] = temp;        return OK;}/* 建造最大堆 */Status BuildHeap(maxheap mh){    for(int i = (mh->size - 2) / 2; i >= 0; i--)        PercDown(mh, i);}/* 交换数组元素 */void Swap(int *pa, int *pb){    int temp = *pa;    *pa = *pb;    *pb = temp;}/* 堆排序 */Status Shell_Sort(int a[], int n){    int i;    maxheap mh;        if(!(mh = (maxheap)malloc(sizeof(struct heap))))        exit(1);    mh->size = 10;    mh->pArray = a;    BuildHeap(mh);        for(i = 0; i < 9; i++) {        Swap(&a[0], &a[mh->size - 1]);        mh->size--;        PercDown(mh, 0);    }        return OK; }int main(){    int i;    int a[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};        for(i = 0; i < sizeof(a) / sizeof(a[0]); i++)        printf("%d ", a[i]);    printf("\n");        Shell_Sort(a, sizeof(a) / sizeof(a[0]));    for(i = 0; i < sizeof(a) / sizeof(a[0]); i++)        printf("%d ", a[i]);    printf("\n");        system("pause");    return 0;}


0 0
原创粉丝点击