Introduction to Algorithms Reading Notes: Bubble Sort, Polynomial Calculation and Horner's Rule Principle Analysis

Question 2-2 Problem Description: The Bubblesort algorithm is a popular sorting algorithm that repeatedly exchanges two adjacent elements in reverse order. Its pseudocode is:

BUBBLESORT (A)
for i ← 1 to length(A)
    for j ← length(A) down to i + 1
        if A[j] < A[j - 1]
            exchange A[j] ↔ A[j - 1]

What is the worst case running time of the bubble sort algorithm?

The running time of the algorithm mainly depends on the for loop in lines 2-4. Given the value of i, the loop performs ni iterations, and the value of i is 1, 2, ..., n, the total number of runs is:


Thinking Questions 2-3 Polynomial Calculations and Horner's Rule: For Polynomial P(n)

\[P(n) = \sum\limits_{k = 0}^n {{a_k}{x^k} = {a_0} + x({a_1} + x({a_2} + ... + x({a_{n - 1}} + x{a_n})))} \]

1. Use direct iterative calculation: the pseudo code is:

sum= 0
for k ← 0
    sum sum + * xk ^ k

For each k, assuming that the exponentiation operation is multiplication of elements multiple times and the addition and multiplication instructions take the same time, the computational complexity of sum+ ak * x ^ k per iteration is k + 2, and the total computational time is: \[ T(n) = {c_1}n + {c_2}((0 + 2) + (1 + 2) + ... + (n + 2)) = {c_1}n + {c_2}\frac{{( n + 1)(n + 4)}}{2}\]

For each k, assuming that the exponentiation operation is multiplication of elements multiple times and the addition and multiplication instructions take the same time, the computational complexity of sum+ ak * x ^ k per iteration is k + 2, and the total computational time is: \[ T(n) = {c_1}n + {c_2}((0 + 2) + (1 + 2) + ... + (n + 2)) = {c_1}n + {c_2}\frac{{( n + 1)(n + 4)}}{2}\]  That is, the time complexity is O(x^2).

2. Compute the polynomial using Horner's rule:

\[P(n) = {a_0} + x({a_1} + x({a_2} + ... + x({a_{n - 1}} + x{a_n})))\]  for the above etc. To calculate the polynomial efficiently, the pseudocode of Horner's rule is:
and ← 0
i ← n
while i >= 0
    do y ← and + x * y
     i  =  i - 1

For each i, its time complexity is 2, then the calculation time of using Horner's rule to calculate the polynomial is: \[T(n) = {c_1}n + {c_2} \times 2 \times n = ({c_1} + 2{c_2})n\] That is, the time complexity is O(n). Compared with direct iterative calculation of polynomials, Horner's rule is much better in time complexity.


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325691587&siteId=291194637