Naive in-place merge
Correctness
naiveInplaceMerge(L,l,m,r): for i←m+1 to r: for j←i down to l+1: if L[j−1]≤L[j]: break swap L[j−1] and L[j]
Lemma 1
Given a sorted list A=[a1,a2,...,aN] with N elements,
where a1≤a2≤...≤aN,
and one value x,
the list L=A∪[x]=[a1,a2,...,aN,x]
(x is appended to the end of list A),
can be sorted by the naive in-place merge method with l=1,m=N,r=N+1.
- Base step: When N=0, list L=[x] is trivially true
- Induction Hypothesis: Suppose this assumption holds when N=k
- Induction Step: When N=k+1
- If x≥L[k], then the L=a1≤a2≤...≤ak≤x is naturally sorted
- Otherwise, x<L[k] and the x and L[k] are swapped.
- Now L[1...k]=[a1,a2,...,ak−1,x]
- By the hypothesis, the naive in-place merge works when N=k, so we can a sorted L[1...k]
- Thus, the list L now is sorted since L[1...k] is sorted
and all its elements are smaller than the current (k+1)th element L[k]
Lemma 2
Given a sorted list A=[a1,a2,...,aN] with N elements
where a1≤a2≤...≤aN,
and B=[b1,b2,...,bM] with M elements
where b1≤b2≤...≤bM,
the list L=A∪B=[a1,a2,...,aN,b1,b2,...,bM]
can be sorted by the above naive in-place merge method with l=1,m=N,r=M+N.
- Base step: When M=1, the condition is same as Lemma 1, so it's true
- Induction Hypothesis: Suppose this assumption holds when M=k
- Induction Step: When M=k+1
- When i=N+1
- the element L[N+1] will be merged with L[1...N]=A
- then the list L[1...N+1] is sorted by Lemma 1
- When i=N+2
- the list is composed by sorted sublists A′=L[1...N+1]
and B′=L[N+2...N+k+1] with k elements
- By the hypothesis, the naive in-place merge works when ∣B′∣=k
- Thus, the list L=A′∪B′=A∪B is sorted
Complexity
O(N2)