Professional Documents
Culture Documents
(CS210/ESO207/ESO211)
Lecture 5
On proving correctness of iterative algorithms
Local minima in a grid (solution from scratch)
L 0;
R n-1;
found FALSE;
while(L R and found = FALSE)
{
mid (L + R)/2;
If (A[mid] = x) found TRUE;
else if(A[mid] < x) L mid + 1;
else R mid - 1
}
if found return mid else return -1;
We need to show:
If found=FALSE, then x is not present in A.
A new approach
Repeat : if current entry is not local minima, move to a neighbor storing smaller value.
j
A new approach
Explore
{ Let c be any entry to start with;
While(c is not a local minima)
{
c a neighbor of c storing smaller value
}
return c;
}
First principle:
Do not discard Explore()
Second principle:
Simplify the problem
9 17 23
i
There is a local minima
in A[0,,i-1]. Give reasons.
Int Local-minima-in-array(A)
{
L 0;
R n-1;
found FALSE;
while( not??
found )
{
mid (L + R)/2;
If (mid is a local minima) found TRUE;
else if(A[mid+1] < A[mid]) L mid+1
??
;
R mid-1
else ??
}
return mid;
10
Execute Explore()
from M[i,mid+1]
9 7
11
L 0;
R n-1;
found FALSE;
while(not found)
{
mid (L + R)/2;
If (M[*,mid] has a local minima) found TRUE;
else { let M[i,mid] be the smallest element in M[*,mid]
if(M[i,mid+1] < M[i,mid]) L mid+1
??
;
else ??R mid-1
}
}
return mid;
O(n) time
O(n) time
O(n)
time
}
12
13
14
15
16
Homework
18
Homework (general)
Merging two sorted arrays:
Given an arrays A storing 2n elements such that A[0,,n-1] is sorted, and
A[n,,2n-1] is also sorted. Design an O(n) time algorithm to sort A.
For example, if A={1,5,17,19,4,5,9,13} in the beginning, then after the
algorithm it should be A={1,4,5,5,9,13,17,19}. Your algorithm may use an
additional array C of size 2n if you wish.
19
Homework (general)
Partitioning an array:
Given an arrays A storing n elements and an element x present in A,
rearrange the elements of A such that if i is the index of x in A, then
A[0,,i-1] contains only elements of A smaller than or equal to x, and
A[i+2,,n-1] contains the rest of the elements of A. Your algorithm may use
only a constant number of additional variables (hence only O(1) extra space is
permitted). Design an O(n) time algorithm for this task.
20
Design an O(n) time algorithm based on the above sketch. For this purpose, you will
need to answer the following question:
How will you take care of the case when A has odd number of elements ?
21
22