2.1 Insertion sort
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'.
Insertion-Sort(A)
for j <- 2 to length(A)
do key = A[j]
//Insert A[j] into the sorted sequence A[1...j-1]
i <- j - 1
while i > 0 and A[i] > key
do A[i+1] = A[i]
i <- i - 1
A[i + 1] <- key
Loop invariants and the correctness of insertion sort.(Initialization, Maintennance, Termination)
Pseudocode conventions.
2.2 Analyzing algorithms
We shall assume a generic one-processor, random-access machine (RAM) model of computation as our implementation technology.
Analysis of insertion sort
The best case: (the array is already sorted) O(n)
The worst case: (the array is in reverse sorted) O(n2)
Order of growth
We usually consider one algorithm to be more efficient than another if its worst-case running time has a lower order of growth.
2.3 Designing algorithms
2.3.1 The divide-and-conquer approach
Divide the problem into a number of subproblems.
Conquer the subproblems by solving them recursively.
Combine the solutions to the subproblems into the solution for the original problem。