1: #include "stdafx.h"
2: #include
3:
4: using namespace std;
5:
6: #define MAX_HEAP_LEN 10
7: int heap[MAX_HEAP_LEN];
8: int heap_size = 0; // the number of elements in heaps
9:
10: void swap(int* a, int* b)
11: {
12: int temp = 0;
13: temp = *b;
14: *b = *a;
15: *a = temp;
16: }
17:
18: void shift_up(int i)
19: {
20: int done = 0;
21: if( i == 0) return; //node is the root already
22: while((i!=0)&&(!done))
23: {
24: if(heap[i] > heap[(i-1)/2])
25: {//if the current is larger than the parent, then swap
26: swap(&heap[i],&heap[(i-1)/2]);
27: }
28: else
29: {// the job is already done.
30: done =1;
31: }
32: i = (i-1)/2;
33: }
34: }
35:
36: void shift_down(int i)
37: {
38: int done = 0;
39: if (2*i + 1> heap_size) return; // node i is a leaf
40:
41: while((2*i+1 < heap_size)&&(!done))
42: {
43: i =2*i+1; // jump to left child
44: if ((i+1< heap_size) && (heap[i+1] > heap[i]))
45: {// find the bigger one of the two children
46: i++;
47: }
48: if (heap[(i-1)/2] < heap[i])
49: {
50: swap(&heap[(i-1)/2], &heap[i]);
51: }
52: else
53: {
54: done = 1;
55: }
56: }
57: }
58:
59: /*
60: void mydelete(int i)
61: {
62: int current = heap[i]; // the one to be deleted
63: int last = heap[heap_size - 1]; // get the last one;
64: heap_size--; // shrink the heap
65: if (i == heap_size) return;
66: heap[i] = last; // use the last item to overwrite the current
67: if(last >= current)
68: shift_up(i);
69: else
70: shift_down(i);
71: }*/
72:
73: int deQueue()
74: {
75: int ret = heap[0]; //堆顶元素出队
76: heap[0]=heap[heap_size -1]; //更新堆顶元素
77: heap_size--; //更新优先级队列大小
78: shift_down(0); //调整优先级队列
79: //mydelete(0);
80: return ret;
81: }
82:
83: void insert(int new_data)
84: {
85: if(heap_size >= MAX_HEAP_LEN) return;
86: heap_size++;
87: heap[heap_size - 1] = new_data;
88: shift_up(heap_size - 1);
89: }
90:
91:
92: int _tmain(int argc, _TCHAR* argv[])
93: {
94: int input[10]={9,3,10,1,2,6,4,5,8,7};
95: for(int i=0; i<10; i++)
96: insert(input[i]);
97:
98: for(int i=0; i<10; i++)
99: cout<<heap[i]<<" ";
100:
101: cout<<endl;
102:
103: for(int i=0; i<10; i++)
104: cout<<deQueue()<<" ";
105:
106: system("pause");
107: return 0;
108: }