Lec9a SpaceComplex
Lec9a SpaceComplex
2/8/2017
Sundar B.
REVIEW: TOP DOWN DESIGN
2/8/2017
e.g.
for i = 1 to N { f(N); }
Sundar B.
where N is input size, and f does not call other procedures
e.g.
8
2/8/2017
Sundar B.
DIVIDE-AND-CONQUER
- RECURSIVE VS. ITERATIVE ALGORITHMS
2/8/2017
Divide-and-Conquer designs translate naturally to
recursive algorithms:
Sundar B.
but recursive algorithms incur stack space overhead.
Solutions?
Can we translate Divide-and-Conquer designs to iterative
algorithms?
10
RECURSIVE VS. ITERATIVE ALGORITHMS – INSERTION SORTING
Problem: Sort, in-place, a list of N elements.
Assume list is stored as an array A[0], A[1], … A[n-1]
2/8/2017
Design : Divide-And-Conquer
Sub-problem: Sort a list of size N-1 (A[0], A[1],…A[n-2])
Sundar B.
Combination: Insert A[n-1] in order (i.e. in the right position)
Termination: when size is <= 1.
insertInOrd(A[n-2],A,n-2)
insertInOrd(A[n-1],A,n-1) insertInOrd(A[1],A,1)
insertSort(A, n) {
11
if (n>1) { insertSort(A,n-1); insertInOrder(A[n-1], A, n-1); }
}
RECURSIVE VS. ITERATIVE ALGORITHMS – INSERTION SORTING
insertInOrd(A[n-2],A,n-2)
Sort(A, n)
…
2/8/2017
Sort(A,n-1) Sort(A,n-2) Sort (A,1)
insertInOrd(A[n-1],A,n-1)
Sundar B.
insertInOrd(A[1],A,1)
Iterative Algorithm
Can be inlined.
insertionSort(A,n) {
M
Sort : A[0] to A[N/2] Sort : A[N/2+1] to A[N-1]
…
MERGE SORTING - DESIGN Merge 1 pair of lists
S [N] of size N/2 each
S[N/2] M S [N/2]
M M M M
14
Merge N/2 pairs of lists of size 1 each
MERGESORT – ITERATIVE ALGORITHM VER.0.5
S [N]
M M M M
slSz=1 15
MERGE SORT – ITERATIVE ALGORITHM VER.0.7
for (slSz=1; slSz<=maxSlSz; slSz*=2) {
//Merging N/(2*slSz) pairs of lists of size slSz each
2/8/2017
for (st1=0; st1<=last; st1+=2*slSz) {
Sundar B.
st2=st1+slSz; en2=st2+slSz-1;
//merging ls[st1..st2-1] with ls[st2..en2]
// and putting the result back in ls[st1..en2]
2/8/2017
st2=st1+slSz; en2=st2+slSz-1;
if (st2 > last) { // Handle uneven-sized sublists
Sundar B.
en2 = last;
if (st2-1 > last) { st2=last+1; }
}
mergeIn(ls, st1, st2, en2);
2/8/2017
/* Postcondition: maxSlSz < n <= 2*maxSlSz */
for (slSz=1; slSz<=maxSlSz; slSz*=2) {
Sundar B.
for (st1=0; st1<=last; st1=st1+2*slSz) {
st2=st1+slSz; en2=st2+slSz-1;
if (st2 > last) { // Handle uneven-sized sublists
en2 = last;
2/8/2017
Algorithm same as ver. 0.9 but, mergeIn uses two arrays, ls1
and ls2:
Sundar B.
in odd iterations of outer loop:
ls1 is an array of sorted sublists:
Exercise:
Write mergeIn to meet this requirement.
Modify mergeSort suitably. 19