Exercises 2.36
Let an array of size
n
, which is in descending order. Consider each time we include an
element
x
into the sorted part. Although we can use a modified binary search algorithm to
find the correct position in
Ο
(
㏒
i) time (assume i is number of elements in the sorted part),
the algorithm still needs to push all the elements in the sorted part oneposition backward
and then insert
x
into the first position of the array. So, when we include
x
we need to:
Ο
(
㏒
i) to find the correct position
Ο
(i) to put it into the correct position
which is
Ο
(i)time
In order to finish the insertion sort, all the elements are needed to be included into the
sorted part:
Σ
i=2 to n
Ο
(i) =
Ο
(n
2
)
To conclude, even we use binary search instead of linear search, the overall worstcase
running time of insertion sort is still
Ο
(n
2
) but not
Θ
(n
㏒
n).
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
Exercises 2.37
The algorithm is as follows:
Assumptions:
S is in an array started from index 0
sizeof(S) = n
Algorithm:
1.
CheckExist(S, x)
2.
MergeSort(S, 0, sizeof(S) –1);
3.
for i = 0 to sizeof(S) – 1
4.
part_of_x = x – S[i]
5.
position = BinarySearch(S, 0, sizeof(S)1, part_of_x)
6.
if position
≠
1 and position
≠
i then
7.
return true
8.
end if
9.
end for
10.
return false
11.
end CheckExist
Analysis:
line 2 takes
Θ
(n
㏒
n)times (from analysis of merge sort)
Within forloop 3:
line 4 takes
This is the end of the preview.
Sign up
to
access the rest of the document.
 Spring '08
 Pearly
 Madrid Metro, Big O notation, θ, 1 j, CheckExist

Click to edit the document details