算法导论(第三版)练习 6.5-1 ~ 6.5-9
6.5-1
略
6.5-2
略
6.5-3
6.5-4
为了正确复用Heap-increase-key中的代码
6.5-5
初始化:显然满足
保持:如果在迭代之前循环不变式为真,那么要么不再进行迭代(A[parent(i)]>A[i]),此时已经保持了循环不变式,要么进行一次交换令A[parent(i)]>A[i],并令i=parent(i)此时也保持了循环不变式,所以迭代之后循环不变式仍然为真。
终止:在停止的时候,原来的A[i](唯一的例外因素)已经被调整到合适的位置,数组整体必定满足A[parent(i)]>A[i]
6.5-6
static increasePriority(A, i, newPriority) { if (newPriority < A[i].priority) { return; } let temp = A[i]; // 待插入元素 temp.priority = newPriority; while (i > 1 && A[Heap.parent(i)].priority < newPriority) { A[i] = A[Heap.parent(i)]; i = Heap.parent(i); } // 寻找合适的插入位置 A[i] = temp; // 插入元素 }
6.5-7
// 用优先队列实现先进先出队列 let queue = new PriorityQueue(); let priorityOfQueue = 100; queue.insertWithPriority("first in", priorityOfQueue--); queue.insertWithPriority("second in", priorityOfQueue--); console.log(queue.pullHighestPriorityElement()); console.log(queue.pullHighestPriorityElement()); /** * output= * first in * second in */ // 用优先队列实现栈 let stack = new PriorityQueue(); let priorityOfStack = 0; stack.insertWithPriority("first in", priorityOfStack++); stack.insertWithPriority("second in", priorityOfStack++); console.log(stack.pullHighestPriorityElement()); console.log(stack.pullHighestPriorityElement()); /** * output= * second in * first in */
6.5-8
略。。
6.5-9