算法:优先级队列

 

优先级队列:

 

 1 #include <stdio.h>

 2 

 3 int A[100];

 4 int heapsize;

 5 

 6 void swap(int i, int j) {

 7     int temp = A[i];

 8     A[i] = A[j];

 9     A[j] = temp;

10 }

11 

12 void huifu(int i){

13     int maxheap = i;

14     int l = 2*i;

15     int r = 2*i + 1;

16     if(l <= heapsize && A[l] > A[maxheap])

17         maxheap = l;

18     if(r <= heapsize && A[r] > A[maxheap])

19         maxheap = r;

20     if(i != maxheap){

21         swap(maxheap, i);

22         huifu(maxheap);

23     }

24 }    

25 

26 

27 void sort(){

28     while(heapsize>1) {

29         swap(heapsize, 1);

30         --heapsize;

31         huifu(1);

32     }

33 }

34 

35 void insert(int x){

36     int i;

37     A[++heapsize] = x;

38     i = heapsize;

39     while(i > 1 && A[i] > A[i/2]) {

40         swap(i, i/2);

41         i >>= 1;

42     }

43     /*

44     while(A[heapsize] > i && i>=0){

45         i/=2;

46         swap(A[heapsize], A[i]);

47     }*/

48 }

49 

50 int  max(){

51     return A[1];

52 }

53 

54 int extract_max(){

55     int tmp = A[1];

56     A[1] = A[heapsize--];

57     huifu(1);

58     return tmp;

59 }

60 

61 void build(){

62     int i;

63     for(i=heapsize/2; i>0 ;--i){

64         huifu(i);

65     }

66 }

67 

68 int main(int argc, char const *argv[])

69 {

70     int n, i;

71     scanf("%d", &n);

72     heapsize = n;

73     for(i=1;i<=n;++i){

74         scanf("%d", &A[i]);

75     }

76     build();

77     sort();

78     // insert(24);

79     // insert(20);

80     // insert(100);

81     for(i = 1; i <= n; i++)

82         printf("%d\n", A[i]);

83     return 0;

84 }

 

你可能感兴趣的:(优先级)