0% found this document useful (0 votes)
29 views12 pages

EELU DS Week2 L1

Uploaded by

khaledsokre
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views12 pages

EELU DS Week2 L1

Uploaded by

khaledsokre
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

By

Dr. Yasser Abdelhamid


y Abdelhamid

 Counting algorithm steps


 Insertion Sort

Dr. Yasser Abdelhamid


y Abdelhamid

 Find T(n) for the following program.

Dr. Yasser Abdelhamid


y Abdelhamid

 How many times does sum++ run?

for(i=4; i<n;i++)
for(j=0; j<=n; j++)
sum++;

I j count
4 0,1,2,…,n n-0+1 = n+1
5 0,1,2,…,n n-0+1 = n+1
… … …
n-1 0,1,2,…,n n-0+1 = n+1

number of times = (n-1 -4 +1) * (n+1)


= (n-4)(n+1) = n(n+1)-4(n+1)

Dr. Yasser Abdelhamid


= n2 – 3n - 4
 O(n2 )
y Abdelhamid

 How many times does sum++ run?

for(i=4; i<n;i++)
for(j=0; j<=i; j++)
sum++;

I j count
4 0,1,2,3,4 5
5 0,1,2,3,4,5 6
… … …
n-1 0…n-1 n

𝑛 𝑛 4
 number of times = 𝑖=5 𝑖 = 𝑖=1 𝑖 - 𝑖=1 𝑖
𝑛(𝑛+1)
 = - 10
2

Dr. Yasser Abdelhamid


1 2
  n
2
  O(n2 )
y Abdelhamid

 An efficient algorithm for sorting a list of


small number of elements
 Works the way many people sort a hand of
playing cards
 Start with an empty left hand and the
cards are on the table
 Then remove one card at a time from the
table and insert it into the correct position
in the left hand.
 To find the correct position for a card, we
compare it with each of the cards already
in the hand, starting from right.

Dr. Yasser Abdelhamid


Abdelhamid
y

Dr. Yasser Abdelhamid


Abdelhamid
y

Dr. Yasser Abdelhamid


y Abdelhamid

Dr. Yasser Abdelhamid


o 𝒕𝒋 denotes the number of times the while loop test in line 5 is executed for that
value of 𝑗.
o Comments are not executable statements, and so they take no time.
y Abdelhamid

 Running Time of Insertion Sort:

 In INSERTION-SORT, the best case occurs


if the array is already sorted.

Dr. Yasser Abdelhamid

You might also like