Beruflich Dokumente
Kultur Dokumente
Lecture 9:
Basic Sorting Algorithms
Tauseef Iftikhar
Department of Computer Science
Government College University, Lahore.
Todays Agenda
Sorting Problem
Insertion Sort Analysis
Bubble Sort Analysis
Selection Sort Analysis
Merge Analysis
Sorting
Pn
j=2 f (j)
Pn
j=2 (f (j)
Line no.
1
2
3
4
5
6
7
8
9
1) +
Iterations
2n
n1
n
Pn 1
f (j)
Pj=2
n
f (j) 1
Pj=2
n
j=2 f (j) 1
n1
Pn
j=2 (f (j)
1)
n(n1)
2
n(n1)
2
Pn
i=1 f (i)
Line no.
1
2
3
4
5
6
Pn
i=1 f (i)
Iterations
2(n + 1)
P
n
f (i)
Pi=1
n
i=1 f (i) 1
g (n)
1 + g (n)
Pn
j=1 f (j)
Line no.
1
2
3
4
5
8
Pn
j=1 f (j)
1 + g (n)
Iterations
2n
n1
Pn1
f (j)
Pj=1
n1
j=1 f (j) 1
g (n)
n1
We see that both loop will run mandatory. Inner loop depends on
outer loop.
f (j) = n j + 1
P
n
i=1
P (n j +
P1)
P
= nj=1 n nj=1 i + nj=1 1
+n
= n2 n(n+1
2
n2 +n
2
=n 2 +n
2
= n2 n2 n2 + n
2
= n2 + n2 = n(n+1)
2
Running time:
T (n) = 4n 2 + n(n+1)
+
2
n(n+1)
2
1 + g (n)
n(n+1)
2