Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (528.36 KB, 4 trang )
Order Notation Warmup
Analyzing Bubble Sort
Sort (a1,…,an):
for i := 1 to n-1
for j := 1 to n-i
if aj>aj+1 then interchange
aj↔aj+1
How many comparison steps as a
function of n?
• Inner loop is executed
n-1 times when i=1
n-2 times when i=2
…
1 time when i=n-1
For a total of 1+2+3+…+(n-2)+(n-1)
=((n-1)∙n)/2.
The exact running time depends on
details of the code (initializations, for
example), the quality of the compiler,
the speed of the computer, etc.
Let T(n) be the maximum running time of
this program for any array of length n.
(Small variations due to whether swaps
actually occur)