算法导论中优先队列选定下标元素增加到k疑惑
1 #define PARENT(i) (i - 1) / 2 2 3 void HEAP-INCREASE-KEY(int* A,int i,int key) 4 { 5 if (key < A[i]) 6 { 7 printf("new key is small than current key"); 8 return; 9 } 10 A[i] = key; 11 while (i > 0 && A[PARENT(i)] < A[i]) 12 { 13 int temp = A[i]; 14 A[i] = A[PARENT(i)]; 15 A[PARENT(i)] = temp; 16 i = PARENT(i); 17 } 18 return; 19 }
但这样真的完全维护了堆的性质了么?
-> A[PARENT(I)] >= A[i]
我觉得并没有,还应在while循环中加一句:
1 while(i > 0 && A[PARENT(i)] < A[i]) 2 { 3 int temp = A[i]; 4 A[i] = A[PARENT(i)]; 5 A[PARENT(i)] = temp; 6 7 //加入的一句算法导论前面的用于堆维护的函数 8 MAX_HEAPIFY(A,i,heap-size); 9 10 i = PARENT(i); 11 }
附上MAX_HEAPIFY(int* A,int i)的函数
#define Left(i) 2 * (i + 1) - 1 #define Right(i) 2* (i + 1) void MAX_HEAPIFY(int* A,int i,int heap-size) { int L = Left(i); int R = Right(i); int large; if (i <= heap-size && A[L] >= A[i]) { large = L; } else large = i; if (i <= heap-size && A[R] >= A[large]) { large = R; } if (large != i) { int temp = A[i]; A[i] = A[large]; A[large] = temp; MAX_HEAPIFY(A,i,heap-size) } else return; }
如果你有正确的思路反驳我,希望能在评论区看见你的身影。