Skip to article frontmatterSkip to article content

Problems

2-1 Insertion sort on small arrays in merge sort

Although merge sort runs in Θ(nlgn)\Theta(n \lg n) worst-case time and insertion sort runs in Θ(n2)\Theta(n^2) worst-case time, the constant factors in insertion sort can make it faster in practice for small problem sizes on many machines. Thus it makes sense to coarsen the leaves of the recursion by using insertion sort within merge sort when subproblems become sufficiently small. Consider a modification to merge sort in which n/kn/k sublists of length kk are sorted using insertion sort and then merged using the standard merging mechanism, where kk is a value to be determined.

2-2 Correctness of bubblesort

Bubblesort is a popular, but inefficient, sorting algorithm. It works by repeatedly swapping adjacent elements that are out of order. The procedure Bubblesort sorts array A[1:n]A[1:n].

1
2
3
4
5
BUBBLESORT(A, n)
  for i = 1 to n - 1
    for j = n downto i + 1
      if A[j] < A[j-1]
        exchange A[j] with A[j-1]

The next two parts prove inequality (1).

2-3 Correctness of Horner’s rule

You are given the coefficents a0,a1,a2,,ana_0, a_1, a_2, \ldots, a_n of a polynomial

P(x)=k=0nakxk=a0+a1x+a2x2++an1xn1+anxn,\begin{align*} P(x) &= \sum_{k=0}^{n}a_kx^k \\ &= a_0 + a_1x + a_2x^2 + \cdots + a_{n-1}x^{n-1} + a_nx^n, \end{align*}

and you want to evaluate this polynomial for a given value of xx. Horner’s rule says to evaluate the polynomial according to this parenthesization:

P(x)=a0+x(a1+x(a2++x(an1+xan)))P(x) = a_0 + x \left( a_1 + x\left( a_2 + \cdots + x\left( a_{n-1} + xa_n \right)\cdots \right) \right)

The procedure Horner implements Horner’s rule to evaluate P(x)P(x), given the coefficients

1
2
3
4
5
HORNER(A,n,x)
  p = 0
  for i = n downto 0
    p = A[i] + x * p
  return p

2-4 Inversions

Let A[1:n]A[1:n] be an array of nn distinct numbers. If i<ji < j and A[i]>A[j]A[i] > A[j], then the pair (i,j)(i, j) is called an inversion of AA.