堆排序

 1 #include<stdio.h>

 2 #include<stdlib.h>

 3 #define OK 1

 4 #define FALSE 0

 5 #define MAX_NUM 100

 6 typedef int Status;

 7 typedef int ElemType;

 8 typedef struct SqList

 9 {

10     ElemType r[MAX_NUM];

11     int length;

12 }SqList;

13 typedef SqList HeapType;

14 Status Exchange(ElemType &a,ElemType &b)

15 {

16     ElemType t;

17     t=a;a=b;b=t;

18     return OK;

19 }

20 void HeapAdjust(HeapType &H,int s,int m)

21 {

22     ElemType rc=H.r[s];

23     for(int j=2*s;j<=m;j*=2)

24     {

25         if(j<m&&H.r[j]<H.r[j+1]) j++;

26         if(rc>=H.r[j]) break;

27         H.r[s]=H.r[j];

28         s=j;

29     }

30     H.r[s]=rc;    

31 } 

32 Status HeapSort(HeapType &H)

33 {

34     for(int i=H.length/2;i>0;i--)

35         HeapAdjust(H,i,H.length);

36     for(int i=H.length;i>1;i--)

37     {

38         Exchange(H.r[1],H.r[i]);

39         HeapAdjust(H,1,i-1);

40     }

41     return OK;

42 }

43 Status main()

44 {

45     HeapType H;

46     puts("请输入待排序数组的元素个数:");

47     scanf("%d",&H.length);

48     puts("请输入你要排序的数组:");

49     for(int i=1;i<=H.length;i++)

50     scanf("%d",&H.r[i]);

51     HeapSort(H);

52     puts("排序后结果为:");

53     for(int i=1;i<=H.length;i++)

54     printf("%-3d",H.r[i]);

55     putchar('\n');

56     system("pause");

57     return OK;

58 } 

你可能感兴趣的:(堆排序)