algorithm binarySearch
input
bottom, top: a number
a: array a[0] to a[n-1] of
numbers
x: a number
output
result:
true if x in a
false otherwise
Sideeffect NA
Plan
if (top < bottom) result := false
else
// get the middle of the array (refining)
middle := (top - bottom)/2 + bottom (refining by +1 or
-1 or integer division …)
// example what is midpoint between 6 and 8
// (8-6)/2 = 1 we need to add 6 to...
Consider the following algorithm. Algorithm Mystery(n) //Input:
A nonnegative integer n S ← 0 for i ← 1 to n do S ← S + i * i
return S a. What does this algorithm compute? b. What is its basic
operation? c. How many times is the basic operation executed? d.
What is the efficiency class of this algorithm? e. Suggest an
improvement, or a better algorithm altogether, and indicate its
efficiency class. If you cannot do it, try...
. We have the following algorithm.
Algorithm Novel(X[0..m-1, 0..m-1])
//Input: A matrix X[0..m-1, 0..m-1] of real numbers
for i←0 to m-2 do
for j←i+1 to m-1 do
if X[i,j] ≠X[j, i]
return false
return true
a. What does this algorithm compute?
b. What is its basic operation?
c. How many times is the basic operation executed?
d. What is the efficiency class of this algorithm?
2. Using matrices, create an algorithm that takes a matrix of
dimension N x N and feed it in a spiral shape with the sequential
number from 1 to N^2.
Then do an algorithm in PSEint
A Mystery Algorithm
Input: An integer n ≥ 1
Output: ??
Find P such that 2 P is the largest power of two less than or
equal to n.
Create a 1-dimensional table with P +1 columns. The leftmost
entry is the Pth column and the rightmost entry is the 0th
column.
Repeat until P < 0
If 2 P ≤ n then
put 1 into column P
set n := n − 2 P
Else
put 0 into column...
A Mystery Algorithm
Input: An integer n ≥ 1
Output: ??
Find P such that 2^p is the largest power of two less
than or equal to n.
Create a 1-dimensional table with P +1 columns. The leftmost
entry is the Pth column
and the rightmost entry is the 0th column.
Repeat until P < 0
If 2^p≤n then
put 1 into column P
set n := n - 2^p
Else
put 0 into column P
End if
Subtract 1...
Consider the following algorithm, which takes as input a
sequence of ?n integers ?1,?2,…,??a1,a2,…,an and produces as output
a matrix ?={???}M={mij} where ???mij is the minim term in the
sequence of integers ??,??+1,…,??ai,ai+1,…,aj for ?≥?j≥i and
???=0mij=0 otherwise.
for i := 1 to n
for j := 1+1 to n
for k:= i+1 to j
m[i][j] := min(m[i][j], a[k])
end for
end for
end for
return m
a.) Show that this algorithm uses ?(?3)O(n3) comparisons to
compute the matrix M....
Consider the following pseudocode for insertion-sort algorithm.
The algorithm sorts an arbitrary array A[0..n − 1] of n
elements.
void ISORT (dtype A[ ], int n) {
int i, j;
for i = 1 to n – 1 {
//Insert A[i] into
the sorted part A[0..i – 1]
j = i;
while (j > 0 and
A[j] < A[j – 1]) {
SWAP (A[j], A[j –
1]);
j = j – 1 }
}...