Introduction to Algorithms, 2nd Edition, P19
Discriptions:
Input: A sequence of n numbers a1, a2, . . .,an.
• Output: A permutation (reordering) a1', a2', ..., an'of the input sequence such that a1' <= a2' <=...<=an'.
Pseudcodes
INSERTION-SORT(A)
1 for j ← 2 to length[A]
2 do key ← A[j]
3 ▹ Insert A[j] into the sorted sequence A[1 j - 1].
4 i ← j - 1
5 while i > 0 and A[i] > key
6 do A[i + 1] ← A[i]
7 i ← i - 1
8 A[i + 1] ← key
My codes in C++:
Analysis:
INSERTION-SORT(A) cost times
1 for j ← 2 to length[A] c1 n
2 do key ← A[j] c2 n - 1
3 ▹ Insert A[j] into the sorted
sequence A[1 j - 1]. 0 n - 1
4 i ← j - 1 c4 n - 1
5 while i > 0 and A[i] > key c5
6 do A[i + 1] ← A[i] c6
7 i ← i - 1 c7
8 A[i + 1] ← key c8 n - 1
The running time of the algorithm is the sum of running times for each statement executed; a
statement that takes ci steps to execute and is executed n times will contribute cin to the total
running time.[5] To compute T(n), the running time of INSERTION-SORT, we sum the
products of the cost and times columns, obtaining
Even for inputs of a given size, an algorithm's running time may depend on which input of
that size is given. For example, in INSERTION-SORT, the best case occurs if the array is
already sorted. For each j = 2, 3, . . . , n, we then find that A[i] ≤ key in line 5 when i has its
initial value of j - 1. Thus tj = 1 for j = 2, 3, . . . , n, and the best-case running time is
T(n) = c1n + c2(n - 1) + c4(n - 1) + c5(n - 1) + c8(n - 1)
= (c1 + c2 + c4 + c5 + c8)n - (c2+ c4 + c5 + c8).
If the array is in reverse sorted order-that is, in decreasing order-the worst case results. We
must compare each element A[j] with each element in the entire sorted subarray A[1 j - 1],
and so tj = j for j = 2, 3, . . . , n. Noting that n*(n+1)/2-1.This worst-case running time can be expressed as an2 + bn + c for constants a, b, and c that again depend on the statement costs ci ; it is thus a quadratic function of n.