exercise

5.1 Max-Heap operations

5.2 Guessing an interval

Choosing two integers has ways: Alice has in total 19900 choices. Consider Bob’s strategy as a decision tree, and each leaf corresponds to a win for Bob. For each question Bob can only halve the search room in the worst case. Thus, in the best algorithm, the search tree is in a complete binary tree, and the height is at least which is greater than , meaning Bob’s always-win strategy in 12 attempts does not exists.

5.3 Counting function calls in recursive functions

a)

b) function

function

5.4 Bubble sort invariant

a) after j-th iteration, the last j elements are sorted and are bigger than all the elements before b)

  1. after the first generation the last element is sorted (or the last element is the largest element) We prove this by induction over the inner loop:
    • IH: the largest element is in the interval after iteration
    • Base case (): After comparing and , the larger of the two elements moves to position 2. Therefore, cannot be the largest element. The largest element must be inside
    • IS:
  • After comparing and , the larger of the two elements moves to position . Therefore, cannot be the largest element. The largest element must be inside By induction, after the first outer loop, the largest element is in and thus must be the last element of the array
  1. Assume the last j elements are sorted and are bigger than all the elements before. In the next iteration the largest element of will be moved to the end of this array, meaning ( elements) are now sorted and are bigger than all the elements before.
  2. after outer iterations, the last elements are sorted, and therefore, all the elements in array are sorted.

5.5

a) a doubly linked list can be used to implement stack efficiently. let pointer head always points to the top of the stack

  • push(x):
    • create a new node ` with value
    • Set .prev=head`
    • Set head.next=n
    • Set head=n
  • pop:
    • set head=head.prev b) a doubly linked list can be used to implement queue efficiently.
  • head → points to the first element.
  • tail → points to the last element.
  • enqueue:
    • create a new node ` with value
    • Set .prev=tail`
    • Set tail.next=n
    • Set tail=n
  • dequeue:
    • Set head=head.next
    • Set head.prev = nullptr