Professional Documents
Culture Documents
max_index = 0;
for in range(len()):
if > A[max_index ]:
max_index =
= 0;
for in range(len()):
if > :
=
= 0;
for in range(len()):
if > :
=
2 9 4 10 5
max 𝑖𝑛𝑑𝑒𝑥 =3
• Finding the maximum in an array
• And swap it with the last element in
Using Recursion!!!
def mySort():
= 0;
for in range(len()):
if > :
=
mySort([:len()-1]
• No Stopping condition
• We are creating a new array in each recursive call of mySort
def mySort(,):
if == 1:
return
= 0;
for in range():
if > :
=
mySort()
BubbleSort Algorithm
A recursive algorithm can be written in a non-recursive manner.
for in range(len()-1):
if > :
=
2 9 4 10 5
𝑖
def bubbleSort():
for in :
for in range(()- ): 1𝑗
if > :
=
BubbleSort Algorithm
Let us do some improvisations in this algorithm.
def bubbleSort():
for in range(1,len())
swap = False
for in range(len()-):
if > :
=
swap = True
if swap == False:
return
2 4 5 10 9
𝑗=1
𝑗=2 No swap
Running Time of An Algorithm
def bubbleSort():
for in range(1,len())
swap = False
for in range(len()-):
if > :
=
swap = True
if swap == False:
return
1 2 3
3 2 1
Running time on the best input
𝑛
1 2 3 4 5 6 7 8
Time Running time on the worst input
𝑛
1 2 3 4 5 6 7 8
Problems with finding running time like this?
• Tedious
• Machine dependent. Different users will come up with different
running times.
Running time
(To simplify, each )
(Assuming )
(To simplify, set )
Time Running time on the worst input
24
20
16
12
𝑛
1 2 3 4 5 6 7
def bubbleSort(): 𝑐 (𝑛 −1)
for in range(1,len())
swap = False
𝑐 (𝑛 −1)
for in range(len()-): 𝑐 (𝑛 −1)
(𝑛 −1)
if > : 𝑐 (𝑛 −1)(𝑛 −1)
= 𝑐 (𝑛 −1)(𝑛 −1)
swap = True 𝑐 (𝑛 −1)(𝑛 −1)
if swap == False: 𝑐 (𝑛 − 1 )
return 0
Running Time
Time
𝑛
1 2 3 4 5 6 7
def bubbleSort(): 𝑐 (𝑛 −1)
for in range(1,len())
swap = False
𝑐 (𝑛 −1)
for in range(len()-): 𝑐 (𝑛 −1)
(𝑛 −2)
if > : 𝑐 (𝑛−1)(𝑛 −2)
= 𝑐 (𝑛−1)(𝑛 −2)
swap = True 𝑐 (𝑛−1)(𝑛 −2)
if swap == False: 0
return 0
𝑛
dominates for all values
dominates for all values
2 2
𝑛 + 2 𝑛 + 2= 𝑂 ( 𝑛 )
Definition: If dominates for all values , then we say
Is ?
Is ?
Observation:
Just look at the highest order term of . Lower order terms of do not matter
for the order notation.
def bubbleSort(): 𝑐 (𝑛 −1)
for in range(1,len())
swap = False
𝑐 (𝑛 −1)
for in range(len()-): 𝑐 (𝑛 −1)
(𝑛 −2)
if > : 𝑐 (𝑛−1)(𝑛 −2)
= 𝑐 (𝑛−1)(𝑛 −2)
swap = True 𝑐 (𝑛−1)(𝑛 −2)
if swap == False: 0
return 0
Running Time
Running Time