SlideShare a Scribd company logo
1 of 49
An Introduction to Programming
though C++
Abhiram G. Ranade
Ch. 16: Arrays and Recursion
Arrays and Recursion
ā€¢ Recursion is very useful for designing
algorithms on sequences
ā€“ Sequences will be stored in arrays
ā€¢ Topics
ā€“ Binary Search
ā€“ Merge Sort
Searching an array
ā€¢ Input: A: int array of length n, x (called ā€œkeyā€) : int
ā€¢ Output: true if x is present in A, false otherwise.
ā€¢ Natural algorithm: scan through the array and return true if found.
for(int i=0; i<n; i++){
if(A[i] == x) return true;
}
return false;
ā€¢ Time consuming:
ā€“ Entire array scanned if the element is not present,
ā€“ Half array scanned on the average if it is present.
ā€¢ Can we possibly do all this with fewer operations?
Searching a sorted array
ā€¢ sorted array: (non decreasing order)
A[0] ā‰¤ A[1] ā‰¤ ā€¦ ā‰¤ A[n-1]
ā€¢ sorted array: (non increasing order)
A[0] ā‰„ A[1] ā‰„ ā€¦ ā‰„ A[n-1]
ā€¢ How do we search in a sorted array (non
increasing or non decreasing)?
ā€“ Does the sortedness help in searching?
Searching for x in
a non decreasing sorted array A[0..n-1]
ā€¢ Key idea for reducing comparisons: First compare x with
the ā€œmiddleā€ element A[n/2] of the array.
ā€¢ Suppose x < A[n/2]:
ā€“ x is also smaller than A[n/2..n-1], because of sorting
ā€“ x if present will be present only in A[0..n/2-1].
ā€“ So in the rest of the algorithm we will only search first half of A.
ā€¢ Suppose x >= A[n/2]:
ā€“ x if present will be present in A[n/2..n-1]
ā€“ Note: x may be present in first half too,
ā€“ In the rest of the algorithm we will only search second half.
ā€¢ How to search the ā€œhalvesā€?
ā€“ Recurse!
Plan
ā€¢ We will write a function Bsearch which will search a
region of an array instead of the entire array.
ā€¢ Region: specified using 2 numbers: starting index S,
length of region L
ā€¢ When L == 1, we are searching a length 1 array.
ā€“ So check if that element, A[S] == x.
ā€¢ Otherwise, compare x to the ā€œmiddleā€ element of
A[S..S+L-1]
ā€“ Middle element: A[S + L/2]
ā€¢ Algorithm is called ā€œBinary searchā€, because size of the
region to be searched gets roughly halved.
The code
bool Bsearch(int A[], int S, int L, int x)
// Search for x in A[S..S+L-1]
{
if(L == 1) return A[S] == x;
int H = L/2;
if(x < A[S+H]) return Bsearch(A, S, H, x);
else return Bsearch(A, S+H, L-H, x);
}
int main(){
int A[8]={-1, 2, 2, 4, 10, 12, 30, 30};
cout << Bsearch(A,0,8,11) << endl;
// searches for 11.
}
How does the algorithm execute?
ā€¢ A = {-1, 2, 2, 4, 10, 12, 30, 30}
ā€¢ First call: Bsearch(A, 0, 8, 11)
ā€“ comparison: 11 < A[0+8/2] = A[4] = 10
ā€“ Is false.
ā€¢ Second call: Bsearch(A, 4, 4, 11)
ā€“ comparison: 11 < A[4+4/2] = A[6] = 30
ā€“ Is true.
ā€¢ Third call: Bsearch(A, 4, 2, 11)
ā€“ comparison: 11 < A[4+2/2] = A[5] = 12
ā€“ Is true.
ā€¢ Fourth call: Bsearch(A, 5, 1, 11)
ā€“ Base case. Return 11 == A[5]. So false.
Proof of correctness 1
Claim: Bsearch(A,S,L,x) returns true Iff x is present in A[S,S+L-1], where 0 <=
S,S+L-1 < length of A, where A is an array sorted in non decreasing order.
Proof: Induction over L.
Base case L = 1. Obvious.
Otherwise: L > 1. Algorithm first computes H = L/2. Note that 0 < H < L.
If x < A[S+H], then x if present must be in A[S,S+H-1]
So algorithm must call Bsearch(A, S, H, x), which it does.
The length argument, H, is smaller than L. So by induction call returns correctly.
If x ā‰„ A[S+H], then x if present, must be in A[S+H, L].
So algorithm must call Bsearch(A, S+H, L-H, x), which it does.
The length argument, L-H, is smaller than L. So by induction call returns correctly.
Hence the algorithm will work correctly for all L.
Remarks
ā€¢ If you are likely to search an array frequently, it is useful to
first sort it. The time to sort the array will be be
compensated by the time saved in subsequent searches.
ā€¢ How do you sort an array in the first place? Next.
ā€¢ Binary search can be written without recursion. Exercise.
ā€¢ Even professional programmers make mistakes when
writing binary search.
ā€“ Should condition use x <= A[H] or x < A[H]?
ā€“ Need to ensure correct even if length is odd.
ā€“ Precise subranges to be searched and precise lengths to be
searched should be exactly correct.
ā€“ Very important to write down precisely what the function does:
ā€œsearches A[S..S+L-1]ā€ ā€“ be careful about -1 etc.
Estimating time taken
ā€¢ General idea: ā€œstandard operationsā€ take 1 cycle.
ā€“ Arithmetic, comparison, copying one word
ā€“ address calculation, pointer dereference
ā€“ Convenient idealization.
ā€¢ We characterize running time as a function of an agreed upon problem
size ā€œnā€:
ā€“ n = Number of keys to be sorted in a sorting problem.
ā€“ n = Size of matrices in matrix multiplication
ā€¢ We worry only how the time grows as the problem size increases: e.g. the
time is ā€œlinearā€ in n or is ā€œquadraticā€ā€¦
ā€“ For large enough problem size, linear e.g. 100n is better than n2/2
ā€“ Computers deal with large problemsā€¦
ā€¢ If time taken is different for different inputs of the same size, we consider
the max time amongst them.
ā€“ We want to claim: ā€œNo matter what the input is, the time is linear in nā€
Sorting
ā€¢ Selection Sort (Chapter 14)
ā€“ Find smallest in A[0..n-1]. Exchange it with A[0].
ā€“ Find smallest in A[1..n-1]. Exchange it with A[1].
ā€“ ā€¦
ā€¢ Selection sort time: we count comparisons
(Other operations will take proportional time.)
ā€“ n-1 comparisons to find smallest
ā€“ n-2 comparisons to find second smallest ā€¦
ā€“ Total n(n-1)/2. ā€œAbout n2ā€. (Quadratic)
ā€¢ Algorithms requiring fewer comparisons are known:
ā€About nlog nā€
ā€¢ One such algorithm is Merge sort.
Mergesort idea
To sort a long sequence:
ā€¢ Break up the sequence into two small sequences.
ā€¢ Sort each small sequence. (Recurse!)
ā€¢ Somehow ā€œmergeā€ the sorted sequences into a
single long sequence.
Hope: ā€œmergingā€ sorted sequences is easier than
sorting the large sequence.
ā€¢ Our hope is correct, as we will see soon!
Example
ā€¢ Suppose we want to sort the sequence
ā€“ 50, 29, 87, 23, 25, 7, 64
ā€¢ Break it into two sequences.
ā€“ 50, 29, 87, 23 and 25, 7, 64.
ā€¢ Sort both
ā€“ We get 23, 29, 50, 87 and 7, 25, 64.
ā€¢ Merge
ā€“ Goal is to get 7, 23, 25, 29, 50, 64, 87.
Merge sort
void mergesort(int S[], int n){
// Sorts sequence S of length n.
if(n==1) return;
int U[n/2], V[n-n/2]; // local arrays
for(int i=0; i<n/2; i++) U[i]=S[i];
for(int i=0; i<n-n/2; i++) V[i]=S[i+n/2];
mergesort(U,n/2);
mergesort(V,n-n/2);
//ā€Mergeā€ sorted U, V into S.
merge(U, n/2, V, n-n/2, S, n);
// U, V merge into original array S.
}
Merging example
U: 23, 29, 50, 87.
V: 7, 25, 64.
S:
ā€¢ The smallest overall must move into S.
ā€¢ Smallest overall = smaller of smallest in U and
smallest in V.
ā€¢ So after movement we get:
U: 23, 29, 50, 87.
V: -, 25, 64.
S: 7.
What do we do next?
U: 23, 29, 50, 87.
V: -, 25, 64.
S: 7.
ā€¢ Now we need to move the second smallest into S.
ā€¢ Second smallest:
ā€“ smallest in U,V after smallest has moved out.
ā€“ smaller of what is at the ā€œfrontā€ of U, V.
ā€¢ So we get:
U: -, 29, 50, 87.
V: -, 25, 64.
S: 7, 23.
General strategy
ā€¢ While both U, V contain a number:
ā€“ Move smallest from those at the head of U,V to the end of S.
ā€¢ If only U contains numbers: move all to end of S.
ā€¢ If only V contains numbers: move all to end of S.
ā€¢ uf: index denoting which element of U is currently at the
front.
ā€“ U[0..uf-1] have moved out.
ā€¢ vf: similarly for V.
ā€¢ sb: index denoting where next element should move into S
next (sb: back of S)
ā€“ S[0..sb-1] contain elements that have moved in earlier.
Merging two sequences
void merge(int U[], int p, int V[], int q, int S[], int n){
// S should receive all elements of U,V, in sorted order.
int uf=0, vf=0; // uf, vf : front of u, v
for(int sb=0; sb < p + q; sb++){ // sb = back of s
//Invariant: s[0..sb-1] contain smallest sb,
// u[uf..p-1], v[vf..q-1] contain rest
if(uf<p && vf<q){ // both U,V are non empty
if(U[uf] < V[vf]){ S[sb] = U[uf]; uf++;}
else{ S[sb] = V[vf]; vf++;}
}
else if(uf < p){ // only U is non empty
S[sb] = U[uf]; uf++;
}
else{ // only V is non empty
S[sb] = V[vf]; vf++;
}
}
}
Time Analysis: merging
Time required to merge two sequences of length
p, q:
ā€¢ Loop runs for p+q iterations.
ā€¢ In each iteration a fixed number of operations
are performed.
ā€¢ So time is proportional to p+q.
ā€¢ Time proportional to n, if n=p+q.
Time analysis: sorting
Ti = maximum time required for mergesort to sort any sequence of length i.
T1 ā‰¤ c, where c is some constant.
Tn ā‰¤ dn + 2Tn/2 + en
dn : time required to create U,V from S.
Tn/2 : time to sort sequences of length n/2. Assume n/2 integer.
en : upper bound on time to merge sequence of net length n.
Tn ā‰¤ fn + 2Tn/2 for f=d+e
Inequality applies to Tn/2 also
Tn/2 ā‰¤ fn/2 + 2Tn/4
Tn ā‰¤ fn + 2(fn/2 + 2Tn/4) = 2fn + 4Tn/4
Continuing we get Tn ā‰¤ kfn + 2kTn/2
k
If n=2k or k = log2 n: Tn ā‰¤ fn log n + nT1 = fnlog2 n + nc
Thus Tnā‰¤ gn log2 n for some constant g.
Remarks
ā€¢ Mergesort is much faster than selection sort in
practice.
The eight queens puzzle
ā€œPlace eight queens on a chess board so that no
queen captures anotherā€.
ā€¢ A queen can capture anything that is in a square
exactly to the East, West, North, South, NE, NW,
SE, SW.
ā€¢ Queens should be in distinct rows, distinct
columns, and distinct ā€œdiagonalsā€
ā€¢ Good example of ā€œconstraint satisfaction
problemā€.
ā€¢ Solution uses recursion.
Can we represent the problem
mathematically?
ā€¢ Frame a question of the form: ā€œFind numbers
x,y,z... such that they satisfy constraints ...ā€
ā€¢ Constraints: equalities, inequalities, ā€¦
ā€¢ It should be possible to interpret the numbers
in terms of queen positions on the board.
Mathematical representation 1
ā€¢ For each board square (i,j), let xij ā€œencodeā€
whether a queen is present or not present in
that square.
xij = 1 : queen present
xij = 0 : queen absent
ā€¢ At most one queen in each row i:
xi1 + xi2 + ... + xin ā‰¤ 1
ā€¢ Similarly for other conditions
ā€¢ ā€œSolveā€!
Example: 3x3 board
ā€¢ Row conditions:
x11+x12+x13 ā‰¤ 1, x21+x22+x23 ā‰¤ 1, x31+x32+x33 ā‰¤ 1
ā€¢ Column conditions:
x11+x21+x31 ā‰¤ 1, x12+x22+x32 ā‰¤ 1, x13+x23+x33 ā‰¤ 1
ā€¢ Diagonal conditions:
x21+x32 ā‰¤ 1, x11+x22+x33 ā‰¤ 1, x12+x23 ā‰¤ 1
x12+x21 ā‰¤ 1, x13+x22+x31 ā‰¤ 1, x23+x32 ā‰¤ 1
ā€¢ Place 3 queens:
x11+x12+x13+x21+x22+x23+x31+x32+x33 = 3
ā€¢ 0-1 constraint:
All xij āˆˆ {0, 1}
Another representation
ā€¢ What do we want to find?
ā€“ Positions for 8 queens.
ā€“ Position in 2d space : 2 numbers, (x, y)
ā€“ Are we looking for 16 numbers then?
ā€¢ Real or integers?
ā€“ Integers, in the range 1..8
ā€¢ Distinct columns:
ā€“ All xi should be distinct.
ā€¢ Distinct rows:
ā€“ All yi should be distinct.
ā€¢ Distinct diagonals:
ā€“ For all i,j where i ā‰  j: |xi - xj| ā‰  |yi ā€“ yj|
Other examples and variations on
constraint satisfaction problems
ā€¢ ā€Find x1, x2, ..., xn such that ...ā€ is called a constraint
satisfaction problem.
ā€¢ 8 queens problem is a constraint satisfaction problem.
ā€¢ Another example: solving equations: find x such that
3x2 + 4x + 1 = 0.
ā€¢ We may in addition have an ā€œobjective functionā€: of all
xi satisfying the constraints, report one that maximizes
some given function f(x1, x2, ..., xn)
ā€¢ Example of a constraint satisfaction problem with an
objective function: finding GCD of x,y.
ā€“ Find r such that r divides x, and r divides y, and f(r)=r is
maximum.
Solving constraint satisfaction
problems
Perform algebraic manipulation and deduce solution.
ā€¢ Quadratic equation: factorize...
ā€œTry all possibilitiesā€
ā€¢ Works if each variable that we want to solve for has a finite domain
ā€“ 8 queens formulation 1: 64 variables, each either 0 or 1
ā€“ 8 queens formulation 2: 16 variables, each from {1,2,...,8}
ā€¢ We construct each candidate solution and check if it satisfies our
constraints. If yes, we report it.
ā€¢ How to construct all solutions?
ā€¢ Arenā€™t there a huge number of them?
ā€“ Number of candidate solutions for 8 queens formulation 1: 264
ā€“ Number of candidate solutions for 8 queens formulation 2: 816
ā€“ 816 = 248 < 264
ā€“ Can we reduce this number further?
Formulation 3
ā€¢ No column can hold more than 1 queen; else there will be captures.
ā€¢ We want 8 queens, need at least 1 queen in each of the 8 columns
ā€¢ So place exactly 1 queen in each column.
New representation: Let yi = row position of queen in column i.
What conditions should y1, y2, ..., y8 satisfy?
ā€¢ Distinct columns condition:
ā€“ Automatically satisfied
ā€¢ Distinct rows condition:
ā€“ yi should be distinct.
ā€¢ Distinct diagonals condition:
ā€“ For all i,j, iā‰ j : |yi - yj| ā‰  |i-j|
ā€¢ Size of search space: 88, much smaller than previous 816 or 264.
A program for 4 queens
int y[4]; // y[i]: row position of column i queen
// For all ways of placing all queens:
for(y[0] = 0; y[0] < 4; y[0]++){
for(y[1] = 0; y[1] < 4; y[1]++){
for(y[2] = 0; y[2] < 4; y[2]++){
for(y[3] = 0; y[3] < 4; y[3]++){
if(!capture(y,4))
cout <<y[0]<<y[1]<<y[2]<<y[3]<<endl;
}
}
}
}
Function to check for capture
bool capture(int y[], int n){
// Decides whether any queen captures any
// other. n = board size.
// check for all pairs j>k
for(int j=1; j<n; j++){
for(int k=0; k<j; k++){
if((y[j] == y[k]) ||
(abs(j-k) == abs(y[j]-y[k]))
return true;
}
}
return false;
} // Loop invariant?
Will the same idea work for any n?
ā€¢ Many programming languages will not allow you
to nest more than a certain number of loops.
ā€¢ In other constraint satisfaction problem, the
number of variables to be selected could be very
large, making it difficult to do so much nesting
ā€¢ Recursion comes to our rescue!
ā€¢ We will write a recursive program which will not
have much nesting but will have the same effect
as writing a program with nesting.
A different view of searching through
the candidate configurations
ā€¢ S = Set of all possible ways (ā€œconfigurationsā€) to place
queens, one queen per column.
= All possible ways to assign values to y0,y1,ā€¦,y7
ā€¢ Suppose n = 3. S has 27 elements:
{000, 001, 002, 010, 011, 012, 020, ā€¦ 222}
Algorithm outline for n = 3 :
ā€¢ Store first configuration in y[0..2], then call capture.
ā€¢ Store second configuration in y[0..2], then call capture.
ā€¢ ā€¦
ā€¢ Store 27th configuration in y[0..2], then call capture.
ā€œSearching the set S of configurationsā€
How to search S
ā€¢ Observation: S = S0 āˆŖ S1 āˆŖ ā€¦ āˆŖ Sn-1, where
ā€“ Si = set of configurations in which queen in column 0 is in
row i, and other queens anywhere.
ā€“ 3 Queens: S0 = {000,001,002,010,011,012,020,021,022}
ā€¢ Searching S = searching S0,ā€¦,Sn-1.
ā€¢ But Si is also a union of smaller sets (recursion!):
ā€¢ Si = Si0 āˆŖ Si1 āˆŖ ā€¦ āˆŖ Si,n-1, where
ā€“ Sij = set of configurations in which queen in column 0 is in
row i, and queen in column 1 in row j, and other queens
anywhere.
ā€¢ What is S02 for the 3 queen problem?
ā€“ {020, 021, 022}
General case
ā€¢ Notational change: We will write S(x) rather
than Sx.
S(i0,i1,ā€¦,ik-1) : Configurations with queens in first
k columns in rows ij for j=0..k-1.
S(i0,i1,ā€¦,ik-1) = S(i0,i1,ā€¦,ik-1,0) āˆŖ S(i0,i1,ā€¦,ik-1,1) āˆŖ
... āˆŖ S(i0,i1,ā€¦,ik-1,n-1)
How to search S (contd.)
void search(int n, int y[], int k){
// n = number of queens, also length of array y.
// Function searches subspace S(y[0],y[1],...y[k-1]) of all candidate
// positions and of these prints those in which there is no capture.
if(k == n){ // base case
if(!capture(y,k)){
for(int j=0; j<k; j++) cout << y[j];
cout << endl;
}
}
else{ // Search S(y[0],...y[k-1]) recursively
for(int j=0; j<n; j++){
y[k] = j; // red decomposition given earlier
search(n, y, k+1);
}
}
}
How to search S (contd)
ā€¢ The function search has an important post condition: it
does not modify y[0..k-1].
ā€¢ Only because of this can we merely set y[k] = j before
recursion.
ā€¢ The main program is natural.
int main(){
const int n=8;
int y[n];
search(n, y, 0);
}
Recursion tree for n=3
Search(3,[-,-,-],0)
Search(3,[0,-,-],1) Search(3,[1,-,-],1) Search(3,[2,-,-],1)
Search(3,[1,0,-],2)
Search(3,[1,1,-],2)
Search(3,[1,2,-],2)
Search(3,[1,2,0],3)
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . .
. . . . . . . . .
An improvement: Early check
S(i0,i1,ā€¦,ik-1) : Set of configurations of k queens such
that queen in column j is in row ij for j=0..k-1.
ā€¢ If any of the first k queens capture each other, we
need not worry about the remaining n-k queens,
clearly there is no non capturing configuration in
this Subspace.
ā€¢ Key idea: whenever we place the kth queen, we
first check if it captures the previous queens.
Only then do we bother to explore the set of
configurations further.
Checking if the kth queen captures any
previous queens
bool lastCaptures(int y[], int k){
// check whether queen in column k
// captures any in columns 0..k-1.
for(int j=0; j<k; j++){
if((y[j] == y[k]) ||
(abs(j-k) == abs(y[j]-y[k]))
return true;
}
return false;
}
Search function and main program
void search(int n, int y[], int k){
if(k == n){
for(int j=0; j<k; j++) cout << y[j];
cout << endl;
}
else {
for(int j=0; j<n; j++){
y[k] = j;
if(!lastCaptures(y,k)) search(n,y,k);
}
}
}
// Precisely state what this function expects and does.
// main program:
// as before.
Remarks
ā€¢ Recursion is very powerful even with arrays.
ā€¢ Idea of mergesort: divide input into parts, sort
each part, then combine, is called ā€œdivide-
conquer-combineā€.
ā€¢ ā€œDivide-conquer-combineā€ is useful for other
problems besides sorting.
ā€¢ ā€œTry out all possibilitiesā€ works for many
problems, see problems at the end of the
chapter.
ā€¢ ā€œEarly condition checkingā€ also works quite often.
Exercise 1
Suppose the comparison in our binary search
code used <= rather than <.
ā€¢ Give an instance (set of input values) for
which the algorithm will produce a wrong
answer.
ā€¢ Where would the proof not work?
Exercise 2
Suppose the binary search code returns the
index of the last element it examines, rather
than a Boolean value. What value would this
be, assuming (1) the element x being searched is
not present in the array, (2) there is exactly one
occurrence of x in the array, (3) there are
multiple occurrences of x?
Exercise 3
Instead of specifying the subarray to be
searched by giving the starting index and the
length, you might give the starting and ending
indices. Write the code using this, and prove its
correctness.
Exercise 4
Suppose I represent a set of integers using an array
that holds the integers in sorted order. Given two
such arrays representing two sets, give an algorithm
that prints their union. (The common elements
must be printed just once.) Your algorithm should
run in time proportional to the size of the union.
Suppose the elements were stored without sorting.
How many comparisons do you think the natural
algorithm would perform? Does sorting help?
Exercise 5
A seller receives bids for an item from n buyers. The seller examines the bids and sells
to the highest bidder. Each buyer b bids Hb if she is happy, and Sb if she is sad. Buyers
are happy/sad with equal probability, and independently of each other. Write a
program that reads in n and the values Hb and Sb for each buyer and prints the
expected value of the winning bid. Your program should do this in two ways, and print
the two answers on separate lines.
1. The probability space has 2n points, corresponding to the different ways in which
the buyers can be happy or sad. Your program should go over each point and
add up the contribution of different points to the expectation. This should be
done using a recursive function, similar to what is used in n queens.
2. What is the probability that the highest in all the numbers H, S actually becomes
the winning bid? What can you say going down the sorted order of bids?
Develop this idea into a very fast algorithm and code that. For sorting, use the
standard library function as discussed in Section 22.3.2. To sort an array of
structures, you should use a ā€œlambda expressionā€ as an extra argument, as
shown at the top of page 321. It is shown for vectors, but is the same for arrays.
Lambda expressions are discussed earlier in the book, and you may find it
interesting to understand them fully.
Exercise 6
The basic idea of binary search can be used even when the values over
which to search are not given explicitly. Here is an example.
The input consists of numbers x1,x2,...,xn which are lengths of
consecutive billboards located along a road. We have an additional
input, k, giving the number of painters available to paint the boards.
Each board requires time proportional to its length to paint. We must
assign some number of consecutive boards to each painter such that
the maximum sum of the length of boards assigned to any painter is as
small as possible, i.e. so as to finish in minimum time.
ā€¢ Observe that it is easy to check whether in T time the k painters can
finish the job.
ā€¢ If the check succeeds, you can decide to check for a lower time T.
ā€¢ Develop this idea into an algorithm that determines the minimum
time. Your algorithm should to about log n checks only.

More Related Content

Similar to ch16 (1).pptx

Counting Sort Lowerbound
Counting Sort LowerboundCounting Sort Lowerbound
Counting Sort Lowerbounddespicable me
Ā 
module2_dIVIDEncONQUER_2022.pdf
module2_dIVIDEncONQUER_2022.pdfmodule2_dIVIDEncONQUER_2022.pdf
module2_dIVIDEncONQUER_2022.pdfShiwani Gupta
Ā 
sorting-160810203705.pptx
sorting-160810203705.pptxsorting-160810203705.pptx
sorting-160810203705.pptxVarchasvaTiwari2
Ā 
Analysis Of Algorithms - Hashing
Analysis Of Algorithms - HashingAnalysis Of Algorithms - Hashing
Analysis Of Algorithms - HashingSam Light
Ā 
introduction to data structures and types
introduction to data structures and typesintroduction to data structures and types
introduction to data structures and typesankita946617
Ā 
Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0BG Java EE Course
Ā 
lecture 11
lecture 11lecture 11
lecture 11sajinsc
Ā 
Theory of Computation "Chapter 1, introduction"
Theory of Computation "Chapter 1, introduction"Theory of Computation "Chapter 1, introduction"
Theory of Computation "Chapter 1, introduction"Ra'Fat Al-Msie'deen
Ā 
lecture 9
lecture 9lecture 9
lecture 9sajinsc
Ā 
Cs1311lecture23wdl
Cs1311lecture23wdlCs1311lecture23wdl
Cs1311lecture23wdlMuhammad Wasif
Ā 
13-hashing.ppt
13-hashing.ppt13-hashing.ppt
13-hashing.pptsoniya555961
Ā 
Mining of massive datasets
Mining of massive datasetsMining of massive datasets
Mining of massive datasetsAshic Mahtab
Ā 
Set theory
Set theorySet theory
Set theoryGaditek
Ā 
CRYPTOGRAPHY AND NUMBER THEORY, he ha huli
CRYPTOGRAPHY AND NUMBER THEORY, he ha huliCRYPTOGRAPHY AND NUMBER THEORY, he ha huli
CRYPTOGRAPHY AND NUMBER THEORY, he ha huliharshmacduacin
Ā 
presentation on important DAG,TRIE,Hashing.pptx
presentation on important DAG,TRIE,Hashing.pptxpresentation on important DAG,TRIE,Hashing.pptx
presentation on important DAG,TRIE,Hashing.pptxjainaaru59
Ā 
Skiena algorithm 2007 lecture06 sorting
Skiena algorithm 2007 lecture06 sortingSkiena algorithm 2007 lecture06 sorting
Skiena algorithm 2007 lecture06 sortingzukun
Ā 

Similar to ch16 (1).pptx (20)

Counting Sort Lowerbound
Counting Sort LowerboundCounting Sort Lowerbound
Counting Sort Lowerbound
Ā 
module2_dIVIDEncONQUER_2022.pdf
module2_dIVIDEncONQUER_2022.pdfmodule2_dIVIDEncONQUER_2022.pdf
module2_dIVIDEncONQUER_2022.pdf
Ā 
sorting-160810203705.pptx
sorting-160810203705.pptxsorting-160810203705.pptx
sorting-160810203705.pptx
Ā 
Analysis Of Algorithms - Hashing
Analysis Of Algorithms - HashingAnalysis Of Algorithms - Hashing
Analysis Of Algorithms - Hashing
Ā 
introduction to data structures and types
introduction to data structures and typesintroduction to data structures and types
introduction to data structures and types
Ā 
Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0
Ā 
lecture 11
lecture 11lecture 11
lecture 11
Ā 
Theory of Computation "Chapter 1, introduction"
Theory of Computation "Chapter 1, introduction"Theory of Computation "Chapter 1, introduction"
Theory of Computation "Chapter 1, introduction"
Ā 
Set theory
Set theorySet theory
Set theory
Ā 
220exercises2
220exercises2220exercises2
220exercises2
Ā 
lecture 9
lecture 9lecture 9
lecture 9
Ā 
Cs1311lecture23wdl
Cs1311lecture23wdlCs1311lecture23wdl
Cs1311lecture23wdl
Ā 
13-hashing.ppt
13-hashing.ppt13-hashing.ppt
13-hashing.ppt
Ā 
Mining of massive datasets
Mining of massive datasetsMining of massive datasets
Mining of massive datasets
Ā 
Set theory
Set theorySet theory
Set theory
Ā 
Tower of Hanoi.ppt
Tower of Hanoi.pptTower of Hanoi.ppt
Tower of Hanoi.ppt
Ā 
CRYPTOGRAPHY AND NUMBER THEORY, he ha huli
CRYPTOGRAPHY AND NUMBER THEORY, he ha huliCRYPTOGRAPHY AND NUMBER THEORY, he ha huli
CRYPTOGRAPHY AND NUMBER THEORY, he ha huli
Ā 
presentation on important DAG,TRIE,Hashing.pptx
presentation on important DAG,TRIE,Hashing.pptxpresentation on important DAG,TRIE,Hashing.pptx
presentation on important DAG,TRIE,Hashing.pptx
Ā 
Skiena algorithm 2007 lecture06 sorting
Skiena algorithm 2007 lecture06 sortingSkiena algorithm 2007 lecture06 sorting
Skiena algorithm 2007 lecture06 sorting
Ā 
Unit vii sorting
Unit   vii sorting Unit   vii sorting
Unit vii sorting
Ā 

Recently uploaded

Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
Ā 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
Ā 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxPooja Bhuva
Ā 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
Ā 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
Ā 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
Ā 
Tatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsTatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsNbelano25
Ā 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
Ā 
Philosophy of china and it's charactistics
Philosophy of china and it's charactisticsPhilosophy of china and it's charactistics
Philosophy of china and it's charactisticshameyhk98
Ā 
80 Đį»€ THI THį»¬ TUYį»‚N SINH TIįŗ¾NG ANH VƀO 10 Sį»ž GD ā€“ ĐT THƀNH PHį» Hį»’ CHƍ MINH NĂ...
80 Đį»€ THI THį»¬ TUYį»‚N SINH TIįŗ¾NG ANH VƀO 10 Sį»ž GD ā€“ ĐT THƀNH PHį» Hį»’ CHƍ MINH NĂ...80 Đį»€ THI THį»¬ TUYį»‚N SINH TIįŗ¾NG ANH VƀO 10 Sį»ž GD ā€“ ĐT THƀNH PHį» Hį»’ CHƍ MINH NĂ...
80 Đį»€ THI THį»¬ TUYį»‚N SINH TIįŗ¾NG ANH VƀO 10 Sį»ž GD ā€“ ĐT THƀNH PHį» Hį»’ CHƍ MINH NĂ...Nguyen Thanh Tu Collection
Ā 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
Ā 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptxJoelynRubio1
Ā 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
Ā 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
Ā 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja Bhuva
Ā 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxmarlenawright1
Ā 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
Ā 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
Ā 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
Ā 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
Ā 

Recently uploaded (20)

Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
Ā 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
Ā 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
Ā 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
Ā 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
Ā 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
Ā 
Tatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsTatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf arts
Ā 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
Ā 
Philosophy of china and it's charactistics
Philosophy of china and it's charactisticsPhilosophy of china and it's charactistics
Philosophy of china and it's charactistics
Ā 
80 Đį»€ THI THį»¬ TUYį»‚N SINH TIįŗ¾NG ANH VƀO 10 Sį»ž GD ā€“ ĐT THƀNH PHį» Hį»’ CHƍ MINH NĂ...
80 Đį»€ THI THį»¬ TUYį»‚N SINH TIįŗ¾NG ANH VƀO 10 Sį»ž GD ā€“ ĐT THƀNH PHį» Hį»’ CHƍ MINH NĂ...80 Đį»€ THI THį»¬ TUYį»‚N SINH TIįŗ¾NG ANH VƀO 10 Sį»ž GD ā€“ ĐT THƀNH PHį» Hį»’ CHƍ MINH NĂ...
80 Đį»€ THI THį»¬ TUYį»‚N SINH TIįŗ¾NG ANH VƀO 10 Sį»ž GD ā€“ ĐT THƀNH PHį» Hį»’ CHƍ MINH NĂ...
Ā 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
Ā 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx
Ā 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
Ā 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
Ā 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Ā 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
Ā 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
Ā 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
Ā 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
Ā 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
Ā 

ch16 (1).pptx

  • 1. An Introduction to Programming though C++ Abhiram G. Ranade Ch. 16: Arrays and Recursion
  • 2. Arrays and Recursion ā€¢ Recursion is very useful for designing algorithms on sequences ā€“ Sequences will be stored in arrays ā€¢ Topics ā€“ Binary Search ā€“ Merge Sort
  • 3. Searching an array ā€¢ Input: A: int array of length n, x (called ā€œkeyā€) : int ā€¢ Output: true if x is present in A, false otherwise. ā€¢ Natural algorithm: scan through the array and return true if found. for(int i=0; i<n; i++){ if(A[i] == x) return true; } return false; ā€¢ Time consuming: ā€“ Entire array scanned if the element is not present, ā€“ Half array scanned on the average if it is present. ā€¢ Can we possibly do all this with fewer operations?
  • 4. Searching a sorted array ā€¢ sorted array: (non decreasing order) A[0] ā‰¤ A[1] ā‰¤ ā€¦ ā‰¤ A[n-1] ā€¢ sorted array: (non increasing order) A[0] ā‰„ A[1] ā‰„ ā€¦ ā‰„ A[n-1] ā€¢ How do we search in a sorted array (non increasing or non decreasing)? ā€“ Does the sortedness help in searching?
  • 5. Searching for x in a non decreasing sorted array A[0..n-1] ā€¢ Key idea for reducing comparisons: First compare x with the ā€œmiddleā€ element A[n/2] of the array. ā€¢ Suppose x < A[n/2]: ā€“ x is also smaller than A[n/2..n-1], because of sorting ā€“ x if present will be present only in A[0..n/2-1]. ā€“ So in the rest of the algorithm we will only search first half of A. ā€¢ Suppose x >= A[n/2]: ā€“ x if present will be present in A[n/2..n-1] ā€“ Note: x may be present in first half too, ā€“ In the rest of the algorithm we will only search second half. ā€¢ How to search the ā€œhalvesā€? ā€“ Recurse!
  • 6. Plan ā€¢ We will write a function Bsearch which will search a region of an array instead of the entire array. ā€¢ Region: specified using 2 numbers: starting index S, length of region L ā€¢ When L == 1, we are searching a length 1 array. ā€“ So check if that element, A[S] == x. ā€¢ Otherwise, compare x to the ā€œmiddleā€ element of A[S..S+L-1] ā€“ Middle element: A[S + L/2] ā€¢ Algorithm is called ā€œBinary searchā€, because size of the region to be searched gets roughly halved.
  • 7. The code bool Bsearch(int A[], int S, int L, int x) // Search for x in A[S..S+L-1] { if(L == 1) return A[S] == x; int H = L/2; if(x < A[S+H]) return Bsearch(A, S, H, x); else return Bsearch(A, S+H, L-H, x); } int main(){ int A[8]={-1, 2, 2, 4, 10, 12, 30, 30}; cout << Bsearch(A,0,8,11) << endl; // searches for 11. }
  • 8. How does the algorithm execute? ā€¢ A = {-1, 2, 2, 4, 10, 12, 30, 30} ā€¢ First call: Bsearch(A, 0, 8, 11) ā€“ comparison: 11 < A[0+8/2] = A[4] = 10 ā€“ Is false. ā€¢ Second call: Bsearch(A, 4, 4, 11) ā€“ comparison: 11 < A[4+4/2] = A[6] = 30 ā€“ Is true. ā€¢ Third call: Bsearch(A, 4, 2, 11) ā€“ comparison: 11 < A[4+2/2] = A[5] = 12 ā€“ Is true. ā€¢ Fourth call: Bsearch(A, 5, 1, 11) ā€“ Base case. Return 11 == A[5]. So false.
  • 9. Proof of correctness 1 Claim: Bsearch(A,S,L,x) returns true Iff x is present in A[S,S+L-1], where 0 <= S,S+L-1 < length of A, where A is an array sorted in non decreasing order. Proof: Induction over L. Base case L = 1. Obvious. Otherwise: L > 1. Algorithm first computes H = L/2. Note that 0 < H < L. If x < A[S+H], then x if present must be in A[S,S+H-1] So algorithm must call Bsearch(A, S, H, x), which it does. The length argument, H, is smaller than L. So by induction call returns correctly. If x ā‰„ A[S+H], then x if present, must be in A[S+H, L]. So algorithm must call Bsearch(A, S+H, L-H, x), which it does. The length argument, L-H, is smaller than L. So by induction call returns correctly. Hence the algorithm will work correctly for all L.
  • 10. Remarks ā€¢ If you are likely to search an array frequently, it is useful to first sort it. The time to sort the array will be be compensated by the time saved in subsequent searches. ā€¢ How do you sort an array in the first place? Next. ā€¢ Binary search can be written without recursion. Exercise. ā€¢ Even professional programmers make mistakes when writing binary search. ā€“ Should condition use x <= A[H] or x < A[H]? ā€“ Need to ensure correct even if length is odd. ā€“ Precise subranges to be searched and precise lengths to be searched should be exactly correct. ā€“ Very important to write down precisely what the function does: ā€œsearches A[S..S+L-1]ā€ ā€“ be careful about -1 etc.
  • 11. Estimating time taken ā€¢ General idea: ā€œstandard operationsā€ take 1 cycle. ā€“ Arithmetic, comparison, copying one word ā€“ address calculation, pointer dereference ā€“ Convenient idealization. ā€¢ We characterize running time as a function of an agreed upon problem size ā€œnā€: ā€“ n = Number of keys to be sorted in a sorting problem. ā€“ n = Size of matrices in matrix multiplication ā€¢ We worry only how the time grows as the problem size increases: e.g. the time is ā€œlinearā€ in n or is ā€œquadraticā€ā€¦ ā€“ For large enough problem size, linear e.g. 100n is better than n2/2 ā€“ Computers deal with large problemsā€¦ ā€¢ If time taken is different for different inputs of the same size, we consider the max time amongst them. ā€“ We want to claim: ā€œNo matter what the input is, the time is linear in nā€
  • 12. Sorting ā€¢ Selection Sort (Chapter 14) ā€“ Find smallest in A[0..n-1]. Exchange it with A[0]. ā€“ Find smallest in A[1..n-1]. Exchange it with A[1]. ā€“ ā€¦ ā€¢ Selection sort time: we count comparisons (Other operations will take proportional time.) ā€“ n-1 comparisons to find smallest ā€“ n-2 comparisons to find second smallest ā€¦ ā€“ Total n(n-1)/2. ā€œAbout n2ā€. (Quadratic) ā€¢ Algorithms requiring fewer comparisons are known: ā€About nlog nā€ ā€¢ One such algorithm is Merge sort.
  • 13. Mergesort idea To sort a long sequence: ā€¢ Break up the sequence into two small sequences. ā€¢ Sort each small sequence. (Recurse!) ā€¢ Somehow ā€œmergeā€ the sorted sequences into a single long sequence. Hope: ā€œmergingā€ sorted sequences is easier than sorting the large sequence. ā€¢ Our hope is correct, as we will see soon!
  • 14. Example ā€¢ Suppose we want to sort the sequence ā€“ 50, 29, 87, 23, 25, 7, 64 ā€¢ Break it into two sequences. ā€“ 50, 29, 87, 23 and 25, 7, 64. ā€¢ Sort both ā€“ We get 23, 29, 50, 87 and 7, 25, 64. ā€¢ Merge ā€“ Goal is to get 7, 23, 25, 29, 50, 64, 87.
  • 15. Merge sort void mergesort(int S[], int n){ // Sorts sequence S of length n. if(n==1) return; int U[n/2], V[n-n/2]; // local arrays for(int i=0; i<n/2; i++) U[i]=S[i]; for(int i=0; i<n-n/2; i++) V[i]=S[i+n/2]; mergesort(U,n/2); mergesort(V,n-n/2); //ā€Mergeā€ sorted U, V into S. merge(U, n/2, V, n-n/2, S, n); // U, V merge into original array S. }
  • 16. Merging example U: 23, 29, 50, 87. V: 7, 25, 64. S: ā€¢ The smallest overall must move into S. ā€¢ Smallest overall = smaller of smallest in U and smallest in V. ā€¢ So after movement we get: U: 23, 29, 50, 87. V: -, 25, 64. S: 7.
  • 17. What do we do next? U: 23, 29, 50, 87. V: -, 25, 64. S: 7. ā€¢ Now we need to move the second smallest into S. ā€¢ Second smallest: ā€“ smallest in U,V after smallest has moved out. ā€“ smaller of what is at the ā€œfrontā€ of U, V. ā€¢ So we get: U: -, 29, 50, 87. V: -, 25, 64. S: 7, 23.
  • 18. General strategy ā€¢ While both U, V contain a number: ā€“ Move smallest from those at the head of U,V to the end of S. ā€¢ If only U contains numbers: move all to end of S. ā€¢ If only V contains numbers: move all to end of S. ā€¢ uf: index denoting which element of U is currently at the front. ā€“ U[0..uf-1] have moved out. ā€¢ vf: similarly for V. ā€¢ sb: index denoting where next element should move into S next (sb: back of S) ā€“ S[0..sb-1] contain elements that have moved in earlier.
  • 19. Merging two sequences void merge(int U[], int p, int V[], int q, int S[], int n){ // S should receive all elements of U,V, in sorted order. int uf=0, vf=0; // uf, vf : front of u, v for(int sb=0; sb < p + q; sb++){ // sb = back of s //Invariant: s[0..sb-1] contain smallest sb, // u[uf..p-1], v[vf..q-1] contain rest if(uf<p && vf<q){ // both U,V are non empty if(U[uf] < V[vf]){ S[sb] = U[uf]; uf++;} else{ S[sb] = V[vf]; vf++;} } else if(uf < p){ // only U is non empty S[sb] = U[uf]; uf++; } else{ // only V is non empty S[sb] = V[vf]; vf++; } } }
  • 20. Time Analysis: merging Time required to merge two sequences of length p, q: ā€¢ Loop runs for p+q iterations. ā€¢ In each iteration a fixed number of operations are performed. ā€¢ So time is proportional to p+q. ā€¢ Time proportional to n, if n=p+q.
  • 21. Time analysis: sorting Ti = maximum time required for mergesort to sort any sequence of length i. T1 ā‰¤ c, where c is some constant. Tn ā‰¤ dn + 2Tn/2 + en dn : time required to create U,V from S. Tn/2 : time to sort sequences of length n/2. Assume n/2 integer. en : upper bound on time to merge sequence of net length n. Tn ā‰¤ fn + 2Tn/2 for f=d+e Inequality applies to Tn/2 also Tn/2 ā‰¤ fn/2 + 2Tn/4 Tn ā‰¤ fn + 2(fn/2 + 2Tn/4) = 2fn + 4Tn/4 Continuing we get Tn ā‰¤ kfn + 2kTn/2 k If n=2k or k = log2 n: Tn ā‰¤ fn log n + nT1 = fnlog2 n + nc Thus Tnā‰¤ gn log2 n for some constant g.
  • 22. Remarks ā€¢ Mergesort is much faster than selection sort in practice.
  • 23. The eight queens puzzle ā€œPlace eight queens on a chess board so that no queen captures anotherā€. ā€¢ A queen can capture anything that is in a square exactly to the East, West, North, South, NE, NW, SE, SW. ā€¢ Queens should be in distinct rows, distinct columns, and distinct ā€œdiagonalsā€ ā€¢ Good example of ā€œconstraint satisfaction problemā€. ā€¢ Solution uses recursion.
  • 24. Can we represent the problem mathematically? ā€¢ Frame a question of the form: ā€œFind numbers x,y,z... such that they satisfy constraints ...ā€ ā€¢ Constraints: equalities, inequalities, ā€¦ ā€¢ It should be possible to interpret the numbers in terms of queen positions on the board.
  • 25. Mathematical representation 1 ā€¢ For each board square (i,j), let xij ā€œencodeā€ whether a queen is present or not present in that square. xij = 1 : queen present xij = 0 : queen absent ā€¢ At most one queen in each row i: xi1 + xi2 + ... + xin ā‰¤ 1 ā€¢ Similarly for other conditions ā€¢ ā€œSolveā€!
  • 26. Example: 3x3 board ā€¢ Row conditions: x11+x12+x13 ā‰¤ 1, x21+x22+x23 ā‰¤ 1, x31+x32+x33 ā‰¤ 1 ā€¢ Column conditions: x11+x21+x31 ā‰¤ 1, x12+x22+x32 ā‰¤ 1, x13+x23+x33 ā‰¤ 1 ā€¢ Diagonal conditions: x21+x32 ā‰¤ 1, x11+x22+x33 ā‰¤ 1, x12+x23 ā‰¤ 1 x12+x21 ā‰¤ 1, x13+x22+x31 ā‰¤ 1, x23+x32 ā‰¤ 1 ā€¢ Place 3 queens: x11+x12+x13+x21+x22+x23+x31+x32+x33 = 3 ā€¢ 0-1 constraint: All xij āˆˆ {0, 1}
  • 27. Another representation ā€¢ What do we want to find? ā€“ Positions for 8 queens. ā€“ Position in 2d space : 2 numbers, (x, y) ā€“ Are we looking for 16 numbers then? ā€¢ Real or integers? ā€“ Integers, in the range 1..8 ā€¢ Distinct columns: ā€“ All xi should be distinct. ā€¢ Distinct rows: ā€“ All yi should be distinct. ā€¢ Distinct diagonals: ā€“ For all i,j where i ā‰  j: |xi - xj| ā‰  |yi ā€“ yj|
  • 28. Other examples and variations on constraint satisfaction problems ā€¢ ā€Find x1, x2, ..., xn such that ...ā€ is called a constraint satisfaction problem. ā€¢ 8 queens problem is a constraint satisfaction problem. ā€¢ Another example: solving equations: find x such that 3x2 + 4x + 1 = 0. ā€¢ We may in addition have an ā€œobjective functionā€: of all xi satisfying the constraints, report one that maximizes some given function f(x1, x2, ..., xn) ā€¢ Example of a constraint satisfaction problem with an objective function: finding GCD of x,y. ā€“ Find r such that r divides x, and r divides y, and f(r)=r is maximum.
  • 29. Solving constraint satisfaction problems Perform algebraic manipulation and deduce solution. ā€¢ Quadratic equation: factorize... ā€œTry all possibilitiesā€ ā€¢ Works if each variable that we want to solve for has a finite domain ā€“ 8 queens formulation 1: 64 variables, each either 0 or 1 ā€“ 8 queens formulation 2: 16 variables, each from {1,2,...,8} ā€¢ We construct each candidate solution and check if it satisfies our constraints. If yes, we report it. ā€¢ How to construct all solutions? ā€¢ Arenā€™t there a huge number of them? ā€“ Number of candidate solutions for 8 queens formulation 1: 264 ā€“ Number of candidate solutions for 8 queens formulation 2: 816 ā€“ 816 = 248 < 264 ā€“ Can we reduce this number further?
  • 30. Formulation 3 ā€¢ No column can hold more than 1 queen; else there will be captures. ā€¢ We want 8 queens, need at least 1 queen in each of the 8 columns ā€¢ So place exactly 1 queen in each column. New representation: Let yi = row position of queen in column i. What conditions should y1, y2, ..., y8 satisfy? ā€¢ Distinct columns condition: ā€“ Automatically satisfied ā€¢ Distinct rows condition: ā€“ yi should be distinct. ā€¢ Distinct diagonals condition: ā€“ For all i,j, iā‰ j : |yi - yj| ā‰  |i-j| ā€¢ Size of search space: 88, much smaller than previous 816 or 264.
  • 31. A program for 4 queens int y[4]; // y[i]: row position of column i queen // For all ways of placing all queens: for(y[0] = 0; y[0] < 4; y[0]++){ for(y[1] = 0; y[1] < 4; y[1]++){ for(y[2] = 0; y[2] < 4; y[2]++){ for(y[3] = 0; y[3] < 4; y[3]++){ if(!capture(y,4)) cout <<y[0]<<y[1]<<y[2]<<y[3]<<endl; } } } }
  • 32. Function to check for capture bool capture(int y[], int n){ // Decides whether any queen captures any // other. n = board size. // check for all pairs j>k for(int j=1; j<n; j++){ for(int k=0; k<j; k++){ if((y[j] == y[k]) || (abs(j-k) == abs(y[j]-y[k])) return true; } } return false; } // Loop invariant?
  • 33. Will the same idea work for any n? ā€¢ Many programming languages will not allow you to nest more than a certain number of loops. ā€¢ In other constraint satisfaction problem, the number of variables to be selected could be very large, making it difficult to do so much nesting ā€¢ Recursion comes to our rescue! ā€¢ We will write a recursive program which will not have much nesting but will have the same effect as writing a program with nesting.
  • 34. A different view of searching through the candidate configurations ā€¢ S = Set of all possible ways (ā€œconfigurationsā€) to place queens, one queen per column. = All possible ways to assign values to y0,y1,ā€¦,y7 ā€¢ Suppose n = 3. S has 27 elements: {000, 001, 002, 010, 011, 012, 020, ā€¦ 222} Algorithm outline for n = 3 : ā€¢ Store first configuration in y[0..2], then call capture. ā€¢ Store second configuration in y[0..2], then call capture. ā€¢ ā€¦ ā€¢ Store 27th configuration in y[0..2], then call capture. ā€œSearching the set S of configurationsā€
  • 35. How to search S ā€¢ Observation: S = S0 āˆŖ S1 āˆŖ ā€¦ āˆŖ Sn-1, where ā€“ Si = set of configurations in which queen in column 0 is in row i, and other queens anywhere. ā€“ 3 Queens: S0 = {000,001,002,010,011,012,020,021,022} ā€¢ Searching S = searching S0,ā€¦,Sn-1. ā€¢ But Si is also a union of smaller sets (recursion!): ā€¢ Si = Si0 āˆŖ Si1 āˆŖ ā€¦ āˆŖ Si,n-1, where ā€“ Sij = set of configurations in which queen in column 0 is in row i, and queen in column 1 in row j, and other queens anywhere. ā€¢ What is S02 for the 3 queen problem? ā€“ {020, 021, 022}
  • 36. General case ā€¢ Notational change: We will write S(x) rather than Sx. S(i0,i1,ā€¦,ik-1) : Configurations with queens in first k columns in rows ij for j=0..k-1. S(i0,i1,ā€¦,ik-1) = S(i0,i1,ā€¦,ik-1,0) āˆŖ S(i0,i1,ā€¦,ik-1,1) āˆŖ ... āˆŖ S(i0,i1,ā€¦,ik-1,n-1)
  • 37. How to search S (contd.) void search(int n, int y[], int k){ // n = number of queens, also length of array y. // Function searches subspace S(y[0],y[1],...y[k-1]) of all candidate // positions and of these prints those in which there is no capture. if(k == n){ // base case if(!capture(y,k)){ for(int j=0; j<k; j++) cout << y[j]; cout << endl; } } else{ // Search S(y[0],...y[k-1]) recursively for(int j=0; j<n; j++){ y[k] = j; // red decomposition given earlier search(n, y, k+1); } } }
  • 38. How to search S (contd) ā€¢ The function search has an important post condition: it does not modify y[0..k-1]. ā€¢ Only because of this can we merely set y[k] = j before recursion. ā€¢ The main program is natural. int main(){ const int n=8; int y[n]; search(n, y, 0); }
  • 39. Recursion tree for n=3 Search(3,[-,-,-],0) Search(3,[0,-,-],1) Search(3,[1,-,-],1) Search(3,[2,-,-],1) Search(3,[1,0,-],2) Search(3,[1,1,-],2) Search(3,[1,2,-],2) Search(3,[1,2,0],3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
  • 40. An improvement: Early check S(i0,i1,ā€¦,ik-1) : Set of configurations of k queens such that queen in column j is in row ij for j=0..k-1. ā€¢ If any of the first k queens capture each other, we need not worry about the remaining n-k queens, clearly there is no non capturing configuration in this Subspace. ā€¢ Key idea: whenever we place the kth queen, we first check if it captures the previous queens. Only then do we bother to explore the set of configurations further.
  • 41. Checking if the kth queen captures any previous queens bool lastCaptures(int y[], int k){ // check whether queen in column k // captures any in columns 0..k-1. for(int j=0; j<k; j++){ if((y[j] == y[k]) || (abs(j-k) == abs(y[j]-y[k])) return true; } return false; }
  • 42. Search function and main program void search(int n, int y[], int k){ if(k == n){ for(int j=0; j<k; j++) cout << y[j]; cout << endl; } else { for(int j=0; j<n; j++){ y[k] = j; if(!lastCaptures(y,k)) search(n,y,k); } } } // Precisely state what this function expects and does. // main program: // as before.
  • 43. Remarks ā€¢ Recursion is very powerful even with arrays. ā€¢ Idea of mergesort: divide input into parts, sort each part, then combine, is called ā€œdivide- conquer-combineā€. ā€¢ ā€œDivide-conquer-combineā€ is useful for other problems besides sorting. ā€¢ ā€œTry out all possibilitiesā€ works for many problems, see problems at the end of the chapter. ā€¢ ā€œEarly condition checkingā€ also works quite often.
  • 44. Exercise 1 Suppose the comparison in our binary search code used <= rather than <. ā€¢ Give an instance (set of input values) for which the algorithm will produce a wrong answer. ā€¢ Where would the proof not work?
  • 45. Exercise 2 Suppose the binary search code returns the index of the last element it examines, rather than a Boolean value. What value would this be, assuming (1) the element x being searched is not present in the array, (2) there is exactly one occurrence of x in the array, (3) there are multiple occurrences of x?
  • 46. Exercise 3 Instead of specifying the subarray to be searched by giving the starting index and the length, you might give the starting and ending indices. Write the code using this, and prove its correctness.
  • 47. Exercise 4 Suppose I represent a set of integers using an array that holds the integers in sorted order. Given two such arrays representing two sets, give an algorithm that prints their union. (The common elements must be printed just once.) Your algorithm should run in time proportional to the size of the union. Suppose the elements were stored without sorting. How many comparisons do you think the natural algorithm would perform? Does sorting help?
  • 48. Exercise 5 A seller receives bids for an item from n buyers. The seller examines the bids and sells to the highest bidder. Each buyer b bids Hb if she is happy, and Sb if she is sad. Buyers are happy/sad with equal probability, and independently of each other. Write a program that reads in n and the values Hb and Sb for each buyer and prints the expected value of the winning bid. Your program should do this in two ways, and print the two answers on separate lines. 1. The probability space has 2n points, corresponding to the different ways in which the buyers can be happy or sad. Your program should go over each point and add up the contribution of different points to the expectation. This should be done using a recursive function, similar to what is used in n queens. 2. What is the probability that the highest in all the numbers H, S actually becomes the winning bid? What can you say going down the sorted order of bids? Develop this idea into a very fast algorithm and code that. For sorting, use the standard library function as discussed in Section 22.3.2. To sort an array of structures, you should use a ā€œlambda expressionā€ as an extra argument, as shown at the top of page 321. It is shown for vectors, but is the same for arrays. Lambda expressions are discussed earlier in the book, and you may find it interesting to understand them fully.
  • 49. Exercise 6 The basic idea of binary search can be used even when the values over which to search are not given explicitly. Here is an example. The input consists of numbers x1,x2,...,xn which are lengths of consecutive billboards located along a road. We have an additional input, k, giving the number of painters available to paint the boards. Each board requires time proportional to its length to paint. We must assign some number of consecutive boards to each painter such that the maximum sum of the length of boards assigned to any painter is as small as possible, i.e. so as to finish in minimum time. ā€¢ Observe that it is easy to check whether in T time the k painters can finish the job. ā€¢ If the check succeeds, you can decide to check for a lower time T. ā€¢ Develop this idea into an algorithm that determines the minimum time. Your algorithm should to about log n checks only.