SlideShare una empresa de Scribd logo
1 de 27
Descargar para leer sin conexión
CCE20003 HGU
CCE20003 PROGRAMMING I
Lecture 15
Spring 2015
ICT Convergence Division
School of Creative Convergence Education
Handong Global University
CCE20003 HGU
OUTLINE
Sorting in Python
Selection sort
Bubble sort
Recursion
CCE20003 HGU
SORTING IN PYTHON
Why sort and search ?
25 -50 % of computing time
- Reporting
- Updating
- Inquiring
In most Python implementations, the sorting algorithm
called Timsort( Tim Peters ,2002) is used, which is a
variant of the merge sort(John von Neumann in 1945).
CCE20003 HGU
>>>L = [4, 2, 3]
>>>L.sort()
>>>print L.sort()
None
>>>print L
[2, 3, 4]
>>>L
[2, 3, 4]
>>>L.sort(reverse = True)
>>>L
[4, 3, 2]
L.sort() does change L.
>>>L = [4, 2, 3]
>>>sorted(L)
[2, 3, 4]
>>>print sorted(L)
[2, 3, 4]
>>print L
[4, 2, 3]
>>>L
[4, 2, 3]
>>>sorted(L, reverse = True)
{4, 3, 2]
sorted(L) does not change L.
CCE20003 HGU
sorted(.) can be used for a sequence
>>>T = (4, 2, 3)
>>>D = {“John” : 24, “Mary” : 20, “James” : 22}
>>>sorted(T)
(2, 3, 4)
>>>sorted(D)
[“James”, “John”, “Mary”]
CCE20003 HGU
SELECTION SORT
BASIC IDEA the smallest element
sorted
s
Step 1
Step k
At the end of the last step
CCE20003 HGU
[5, 9, 4, 7, 3] 4 comparisons
[3, 9, 5, 7, 4] 3 comparisons
[3, 4, 9, 7, 5] 2 comparisons Why ?
[3, 4, 5, 9, 7] 1 comparison
[3, 4, 5, 7, 9]
[3, 4, 5, 7, 9]
How many comparisons in
general?
(n-1)n/ 2 = 𝑛2/2 – n/2
O( 𝑛2)
4(4 +1)/2
comparisons
CCE20003 HGU
1 + 2 + 3 + 4 = 4 (4 + 1) = 10 comparisons
In general,
1 + ……… + (n - 1) = (n - 1)(n – 1 + 1)/2 = (n -1)n/2,
where n = len(L).
CCE20003 HGU
Pseudo code
1. Given a list of elements, find the smallest element
and make it the first element of the list. Let the sub-
list except the first element be the remaining list.
2. Given the remaining list, find the smallest element
and make it the first element of the remaining list. Make
a new remaining list by excluding the first element.
3. Repeat Step 2 until the remaining list becomes a
single element.
CCE20003 HGU
def selection_sort(L):
start = 0
end = len(L)
while start < end:
for i in range(start, end):
if L[i] < L[start]:
L[start], L[i] = L[i], L[start]
start += 1 for the next sub-list
return L
Finding the smallest
one in the current
sub-list
How about start , end -1 ?
CCE20003 HGU
BUBBLE SORT
Basic idea
1st round
Like a bubble floating up!
5
9
4
7
3
5
9
4
3
7
5
9
3
4
7
5
3
9
4
7
3
5
9
4
7
4 comparisons
CCE20003 HGU
2nd round
3
5
9
4
7
3
5
9
4
7
3
5
4
9
7
3
4
5
9
7
3 comparisons
CCE20003 HGU
3rd round
3
4
5
9
7
3
4
5
7
9
3
4
5
7
9
2 comparisons
CCE20003 HGU
4th round
3
4
5
7
9
3
4
5
7
9
3
4
5
7
9
1 comparisons
CCE20003 HGU
Pseudo code
1.Enumerate a series of sub-lists of a list of elements,
each sub-list containing the elements from the i-th one
to the last one for i = 0, 1, 2, 3, ……, n-1
2. For each sub-list, scan the sub-list in the reverse order
from the end, compare every consecutive pair of elements,
and swap the elements, if needed, to make the smaller
one float up.
3. Stop when all sub-lists are scanned.
CCE20003 HGU
def bubble_sort(L):
for i in range ( len(L) - 1):
for j in range(len(L) - 1 - i):
i1 = (len(L)-1) - (j + 1)
i2 = (len(L)-1) - j
if L[i1] > L[i2]:
L[i1], L[i2] = L[i2], L[i1]
return L
Bubbles float up!
Sort a sub-list.
CCE20003 HGU
RECURSION
Recursion is defining something in terms of itself. It
sounds a bit odd, but very natural in fact. Here are
some examples:
According to the legal code of United States, a U.S.
citizen is
1. any child born inside United States, or
the base case
2. any child born outside United States and at least
one of whose parent is a U.S. citizen satisfying certain
condition.
the recursive(inductive) case
CCE20003 HGU
In mathematics, the factorial function is defined as
follows:
f(n) = n X (n-1) X (n-2) X……….X 2 X 1
(n – 1)!
f(n – 1)
1 if n = 1 base case
n x f(n - 1) if n > 1 recursive case
f(n)
f(n) =
CCE20003 HGU
Fibonacci numbers
1 if n = 0
1 if n = 1
f(n – 1) + f(n - 2)
f(n)
base case
recursive case
n f(n)
0 1
1 1
2 2
3 3
4 5
5 8
6 13
…… ……
CCE20003 HGU
Recursive functions
A function is said to be recursive if the function is
defined in terms of itself, specifically, the function
can call itself during its execution.
CCE20003 HGU
Factorial function
1 if n = 1 base case
n x f(n - 1) if n > 1 recursive case
f(n)
def fact(n):
if n == 1:
return 1
return n * fact(n-1)
def fact(n):
result = 1
while n >1:
result = result * n
n -= 1
return result
f(n) =
CCE20003 HGU
def fact(n):
if n == 1:
print 1,
return 1
else:
print n, "x ",
return n * fact(n-1)
x = fact(7)
print “ = “, x
7 x 6 x 5 x 4 x 3 x 2 x 1 = 5040
CCE20003 HGU
Fibonacci numbers
1 if n = 0
1 if n = 1
f(n – 1) + f(n - 2)
f(n)
base case
recursive case
def fib(n):
if n == 0 or n == 1:
return 1
else:
return fib(n – 1) + fib(n - 2)
fib(5)
CCE20003 HGU
def fib(n):
global lv
lv += 1
if n == 0 or n == 1:
print " " * 4 * lv, 1
lv -= 1
return 1
else:
print " " * 4 * lv, "fib(", n,")"
x = fib(n - 1) + fib(n - 2)
lv -= 1
return x
lv = -1
x = fib(5)
print “n“, ”fib(5) = ", x
fib( 5 )
fib( 4 )
fib( 3 )
fib( 2 )
1
1
1
fib( 2 )
1
1
fib( 3 )
fib( 2 )
1
1
1
fib(5) = 8
CCE20003 HGU
8
5 3
3 2 2 1
2 1 1 1 1 1
1 1
Fib(5)
Fib(4) Fib(3)
Fib(3) Fib(2)
Fib(2)
Fib(2)
CCE20003 HGU
Palindromes
def is_palin(s):
if len(s) <= 1:
return True
else:
return (s[0] == s[-1]) and is_palin(s[1, -1])
palin(s) =
True if n <= 1 base case
(s[0] == s[-1]) and palin(s[1: -1]) if n > 1
recursive case
CCE20003 HGU
doggod
oggo
gg
True
True
True
True
def is_palin(s):
global lv
lv += 1
if len(s) <= 1:
display(True)
lv -= 1
return True
else:
display(s)
flag = (s[0] == s[-1]) and
is_palin(s[1 : -1])
display(flag)
lv -= 1
return flag
def display(s):
global lv
if lv == 0:
print s
else:
print " " * 4 * lv, s
lv = -1
is_palin( "dogGod".lower())

Más contenido relacionado

Similar a lecture.15.note.pptx

Numpy発表資料 tokyoscipy
Numpy発表資料 tokyoscipyNumpy発表資料 tokyoscipy
Numpy発表資料 tokyoscipyHiroaki Hamada
 
Python cheatsheat.pdf
Python cheatsheat.pdfPython cheatsheat.pdf
Python cheatsheat.pdfHimoZZZ
 
Brief summary of signals
Brief summary of signalsBrief summary of signals
Brief summary of signalsaroosa khan
 
differential-calculus-1-23.pdf
differential-calculus-1-23.pdfdifferential-calculus-1-23.pdf
differential-calculus-1-23.pdfIILSASTOWER
 
CMSC 56 | Lecture 12: Recursive Definition & Algorithms, and Program Correctness
CMSC 56 | Lecture 12: Recursive Definition & Algorithms, and Program CorrectnessCMSC 56 | Lecture 12: Recursive Definition & Algorithms, and Program Correctness
CMSC 56 | Lecture 12: Recursive Definition & Algorithms, and Program Correctnessallyn joy calcaben
 
Learning Deep Learning
Learning Deep LearningLearning Deep Learning
Learning Deep Learningsimaokasonse
 
funwithalgorithms.pptx
funwithalgorithms.pptxfunwithalgorithms.pptx
funwithalgorithms.pptxTess Ferrandez
 
Forward & Backward Differenece Table
Forward & Backward Differenece TableForward & Backward Differenece Table
Forward & Backward Differenece TableSaloni Singhal
 
Learn from LL(1) to PEG parser the hard way
Learn from LL(1) to PEG parser the hard wayLearn from LL(1) to PEG parser the hard way
Learn from LL(1) to PEG parser the hard wayKir Chou
 
Alg2 lesson 10-4 and 10-5
Alg2 lesson 10-4 and 10-5Alg2 lesson 10-4 and 10-5
Alg2 lesson 10-4 and 10-5Carol Defreese
 
Docslide.us 2002 formulae-and-tables
Docslide.us 2002 formulae-and-tablesDocslide.us 2002 formulae-and-tables
Docslide.us 2002 formulae-and-tablesbarasActuarial
 
Recursion - Computer Algorithms
Recursion - Computer AlgorithmsRecursion - Computer Algorithms
Recursion - Computer AlgorithmsAlaa Al-Makhzoomy
 
Review session2
Review session2Review session2
Review session2NEEDY12345
 

Similar a lecture.15.note.pptx (20)

Numpy発表資料 tokyoscipy
Numpy発表資料 tokyoscipyNumpy発表資料 tokyoscipy
Numpy発表資料 tokyoscipy
 
Recursion
RecursionRecursion
Recursion
 
Python cheatsheat.pdf
Python cheatsheat.pdfPython cheatsheat.pdf
Python cheatsheat.pdf
 
Brief summary of signals
Brief summary of signalsBrief summary of signals
Brief summary of signals
 
differential-calculus-1-23.pdf
differential-calculus-1-23.pdfdifferential-calculus-1-23.pdf
differential-calculus-1-23.pdf
 
CMSC 56 | Lecture 12: Recursive Definition & Algorithms, and Program Correctness
CMSC 56 | Lecture 12: Recursive Definition & Algorithms, and Program CorrectnessCMSC 56 | Lecture 12: Recursive Definition & Algorithms, and Program Correctness
CMSC 56 | Lecture 12: Recursive Definition & Algorithms, and Program Correctness
 
Learning Deep Learning
Learning Deep LearningLearning Deep Learning
Learning Deep Learning
 
Sorting
SortingSorting
Sorting
 
ch3.ppt
ch3.pptch3.ppt
ch3.ppt
 
funwithalgorithms.pptx
funwithalgorithms.pptxfunwithalgorithms.pptx
funwithalgorithms.pptx
 
FACTORING
FACTORINGFACTORING
FACTORING
 
Forward & Backward Differenece Table
Forward & Backward Differenece TableForward & Backward Differenece Table
Forward & Backward Differenece Table
 
Learn from LL(1) to PEG parser the hard way
Learn from LL(1) to PEG parser the hard wayLearn from LL(1) to PEG parser the hard way
Learn from LL(1) to PEG parser the hard way
 
Alg2 lesson 10-4 and 10-5
Alg2 lesson 10-4 and 10-5Alg2 lesson 10-4 and 10-5
Alg2 lesson 10-4 and 10-5
 
Lab no.07
Lab no.07Lab no.07
Lab no.07
 
Python Programming
Python Programming Python Programming
Python Programming
 
Docslide.us 2002 formulae-and-tables
Docslide.us 2002 formulae-and-tablesDocslide.us 2002 formulae-and-tables
Docslide.us 2002 formulae-and-tables
 
Recursion - Computer Algorithms
Recursion - Computer AlgorithmsRecursion - Computer Algorithms
Recursion - Computer Algorithms
 
Review session2
Review session2Review session2
Review session2
 
Si math 107 ch5,8
Si math 107 ch5,8Si math 107 ch5,8
Si math 107 ch5,8
 

Más de JibrilJundi

Más de JibrilJundi (11)

1. Ideal and Actual Cycle.pptx
1. Ideal and Actual Cycle.pptx1. Ideal and Actual Cycle.pptx
1. Ideal and Actual Cycle.pptx
 
Ass 1.pdf
Ass 1.pdfAss 1.pdf
Ass 1.pdf
 
4.ppt
4.ppt4.ppt
4.ppt
 
blast furnace.pptx
blast furnace.pptxblast furnace.pptx
blast furnace.pptx
 
chapter 2.pptx
chapter 2.pptxchapter 2.pptx
chapter 2.pptx
 
ch.4.pptx
ch.4.pptxch.4.pptx
ch.4.pptx
 
CH 3.pptx
CH 3.pptxCH 3.pptx
CH 3.pptx
 
Thermo I CH 2.pptx
Thermo I CH 2.pptxThermo I CH 2.pptx
Thermo I CH 2.pptx
 
Thermo I CH 1.pptx
Thermo I CH 1.pptxThermo I CH 1.pptx
Thermo I CH 1.pptx
 
dynamics chapter 2.pptx
dynamics chapter 2.pptxdynamics chapter 2.pptx
dynamics chapter 2.pptx
 
dynamics chapt 1 .pptx
dynamics chapt 1 .pptxdynamics chapt 1 .pptx
dynamics chapt 1 .pptx
 

Último

English-8-Q4-W3-Synthesizing-Essential-Information-From-Various-Sources-1.pdf
English-8-Q4-W3-Synthesizing-Essential-Information-From-Various-Sources-1.pdfEnglish-8-Q4-W3-Synthesizing-Essential-Information-From-Various-Sources-1.pdf
English-8-Q4-W3-Synthesizing-Essential-Information-From-Various-Sources-1.pdfblazblazml
 
Data Analysis Project Presentation: Unveiling Your Ideal Customer, Bank Custo...
Data Analysis Project Presentation: Unveiling Your Ideal Customer, Bank Custo...Data Analysis Project Presentation: Unveiling Your Ideal Customer, Bank Custo...
Data Analysis Project Presentation: Unveiling Your Ideal Customer, Bank Custo...Boston Institute of Analytics
 
Non Text Magic Studio Magic Design for Presentations L&P.pdf
Non Text Magic Studio Magic Design for Presentations L&P.pdfNon Text Magic Studio Magic Design for Presentations L&P.pdf
Non Text Magic Studio Magic Design for Presentations L&P.pdfPratikPatil591646
 
Bank Loan Approval Analysis: A Comprehensive Data Analysis Project
Bank Loan Approval Analysis: A Comprehensive Data Analysis ProjectBank Loan Approval Analysis: A Comprehensive Data Analysis Project
Bank Loan Approval Analysis: A Comprehensive Data Analysis ProjectBoston Institute of Analytics
 
6 Tips for Interpretable Topic Models _ by Nicha Ruchirawat _ Towards Data Sc...
6 Tips for Interpretable Topic Models _ by Nicha Ruchirawat _ Towards Data Sc...6 Tips for Interpretable Topic Models _ by Nicha Ruchirawat _ Towards Data Sc...
6 Tips for Interpretable Topic Models _ by Nicha Ruchirawat _ Towards Data Sc...Dr Arash Najmaei ( Phd., MBA, BSc)
 
Presentation of project of business person who are success
Presentation of project of business person who are successPresentation of project of business person who are success
Presentation of project of business person who are successPratikSingh115843
 
Statistics For Management by Richard I. Levin 8ed.pdf
Statistics For Management by Richard I. Levin 8ed.pdfStatistics For Management by Richard I. Levin 8ed.pdf
Statistics For Management by Richard I. Levin 8ed.pdfnikeshsingh56
 
Decoding Movie Sentiments: Analyzing Reviews with Data Analysis model
Decoding Movie Sentiments: Analyzing Reviews with Data Analysis modelDecoding Movie Sentiments: Analyzing Reviews with Data Analysis model
Decoding Movie Sentiments: Analyzing Reviews with Data Analysis modelBoston Institute of Analytics
 
Digital Marketing Plan, how digital marketing works
Digital Marketing Plan, how digital marketing worksDigital Marketing Plan, how digital marketing works
Digital Marketing Plan, how digital marketing worksdeepakthakur548787
 
DATA ANALYSIS using various data sets like shoping data set etc
DATA ANALYSIS using various data sets like shoping data set etcDATA ANALYSIS using various data sets like shoping data set etc
DATA ANALYSIS using various data sets like shoping data set etclalithasri22
 
IBEF report on the Insurance market in India
IBEF report on the Insurance market in IndiaIBEF report on the Insurance market in India
IBEF report on the Insurance market in IndiaManalVerma4
 
Role of Consumer Insights in business transformation
Role of Consumer Insights in business transformationRole of Consumer Insights in business transformation
Role of Consumer Insights in business transformationAnnie Melnic
 
Digital Indonesia Report 2024 by We Are Social .pdf
Digital Indonesia Report 2024 by We Are Social .pdfDigital Indonesia Report 2024 by We Are Social .pdf
Digital Indonesia Report 2024 by We Are Social .pdfNicoChristianSunaryo
 
why-transparency-and-traceability-are-essential-for-sustainable-supply-chains...
why-transparency-and-traceability-are-essential-for-sustainable-supply-chains...why-transparency-and-traceability-are-essential-for-sustainable-supply-chains...
why-transparency-and-traceability-are-essential-for-sustainable-supply-chains...Jack Cole
 

Último (17)

English-8-Q4-W3-Synthesizing-Essential-Information-From-Various-Sources-1.pdf
English-8-Q4-W3-Synthesizing-Essential-Information-From-Various-Sources-1.pdfEnglish-8-Q4-W3-Synthesizing-Essential-Information-From-Various-Sources-1.pdf
English-8-Q4-W3-Synthesizing-Essential-Information-From-Various-Sources-1.pdf
 
Data Analysis Project Presentation: Unveiling Your Ideal Customer, Bank Custo...
Data Analysis Project Presentation: Unveiling Your Ideal Customer, Bank Custo...Data Analysis Project Presentation: Unveiling Your Ideal Customer, Bank Custo...
Data Analysis Project Presentation: Unveiling Your Ideal Customer, Bank Custo...
 
Non Text Magic Studio Magic Design for Presentations L&P.pdf
Non Text Magic Studio Magic Design for Presentations L&P.pdfNon Text Magic Studio Magic Design for Presentations L&P.pdf
Non Text Magic Studio Magic Design for Presentations L&P.pdf
 
Bank Loan Approval Analysis: A Comprehensive Data Analysis Project
Bank Loan Approval Analysis: A Comprehensive Data Analysis ProjectBank Loan Approval Analysis: A Comprehensive Data Analysis Project
Bank Loan Approval Analysis: A Comprehensive Data Analysis Project
 
6 Tips for Interpretable Topic Models _ by Nicha Ruchirawat _ Towards Data Sc...
6 Tips for Interpretable Topic Models _ by Nicha Ruchirawat _ Towards Data Sc...6 Tips for Interpretable Topic Models _ by Nicha Ruchirawat _ Towards Data Sc...
6 Tips for Interpretable Topic Models _ by Nicha Ruchirawat _ Towards Data Sc...
 
Presentation of project of business person who are success
Presentation of project of business person who are successPresentation of project of business person who are success
Presentation of project of business person who are success
 
Statistics For Management by Richard I. Levin 8ed.pdf
Statistics For Management by Richard I. Levin 8ed.pdfStatistics For Management by Richard I. Levin 8ed.pdf
Statistics For Management by Richard I. Levin 8ed.pdf
 
Decoding Movie Sentiments: Analyzing Reviews with Data Analysis model
Decoding Movie Sentiments: Analyzing Reviews with Data Analysis modelDecoding Movie Sentiments: Analyzing Reviews with Data Analysis model
Decoding Movie Sentiments: Analyzing Reviews with Data Analysis model
 
Digital Marketing Plan, how digital marketing works
Digital Marketing Plan, how digital marketing worksDigital Marketing Plan, how digital marketing works
Digital Marketing Plan, how digital marketing works
 
Insurance Churn Prediction Data Analysis Project
Insurance Churn Prediction Data Analysis ProjectInsurance Churn Prediction Data Analysis Project
Insurance Churn Prediction Data Analysis Project
 
DATA ANALYSIS using various data sets like shoping data set etc
DATA ANALYSIS using various data sets like shoping data set etcDATA ANALYSIS using various data sets like shoping data set etc
DATA ANALYSIS using various data sets like shoping data set etc
 
IBEF report on the Insurance market in India
IBEF report on the Insurance market in IndiaIBEF report on the Insurance market in India
IBEF report on the Insurance market in India
 
Role of Consumer Insights in business transformation
Role of Consumer Insights in business transformationRole of Consumer Insights in business transformation
Role of Consumer Insights in business transformation
 
2023 Survey Shows Dip in High School E-Cigarette Use
2023 Survey Shows Dip in High School E-Cigarette Use2023 Survey Shows Dip in High School E-Cigarette Use
2023 Survey Shows Dip in High School E-Cigarette Use
 
Data Analysis Project: Stroke Prediction
Data Analysis Project: Stroke PredictionData Analysis Project: Stroke Prediction
Data Analysis Project: Stroke Prediction
 
Digital Indonesia Report 2024 by We Are Social .pdf
Digital Indonesia Report 2024 by We Are Social .pdfDigital Indonesia Report 2024 by We Are Social .pdf
Digital Indonesia Report 2024 by We Are Social .pdf
 
why-transparency-and-traceability-are-essential-for-sustainable-supply-chains...
why-transparency-and-traceability-are-essential-for-sustainable-supply-chains...why-transparency-and-traceability-are-essential-for-sustainable-supply-chains...
why-transparency-and-traceability-are-essential-for-sustainable-supply-chains...
 

lecture.15.note.pptx

  • 1. CCE20003 HGU CCE20003 PROGRAMMING I Lecture 15 Spring 2015 ICT Convergence Division School of Creative Convergence Education Handong Global University
  • 2. CCE20003 HGU OUTLINE Sorting in Python Selection sort Bubble sort Recursion
  • 3. CCE20003 HGU SORTING IN PYTHON Why sort and search ? 25 -50 % of computing time - Reporting - Updating - Inquiring In most Python implementations, the sorting algorithm called Timsort( Tim Peters ,2002) is used, which is a variant of the merge sort(John von Neumann in 1945).
  • 4. CCE20003 HGU >>>L = [4, 2, 3] >>>L.sort() >>>print L.sort() None >>>print L [2, 3, 4] >>>L [2, 3, 4] >>>L.sort(reverse = True) >>>L [4, 3, 2] L.sort() does change L. >>>L = [4, 2, 3] >>>sorted(L) [2, 3, 4] >>>print sorted(L) [2, 3, 4] >>print L [4, 2, 3] >>>L [4, 2, 3] >>>sorted(L, reverse = True) {4, 3, 2] sorted(L) does not change L.
  • 5. CCE20003 HGU sorted(.) can be used for a sequence >>>T = (4, 2, 3) >>>D = {“John” : 24, “Mary” : 20, “James” : 22} >>>sorted(T) (2, 3, 4) >>>sorted(D) [“James”, “John”, “Mary”]
  • 6. CCE20003 HGU SELECTION SORT BASIC IDEA the smallest element sorted s Step 1 Step k At the end of the last step
  • 7. CCE20003 HGU [5, 9, 4, 7, 3] 4 comparisons [3, 9, 5, 7, 4] 3 comparisons [3, 4, 9, 7, 5] 2 comparisons Why ? [3, 4, 5, 9, 7] 1 comparison [3, 4, 5, 7, 9] [3, 4, 5, 7, 9] How many comparisons in general? (n-1)n/ 2 = 𝑛2/2 – n/2 O( 𝑛2) 4(4 +1)/2 comparisons
  • 8. CCE20003 HGU 1 + 2 + 3 + 4 = 4 (4 + 1) = 10 comparisons In general, 1 + ……… + (n - 1) = (n - 1)(n – 1 + 1)/2 = (n -1)n/2, where n = len(L).
  • 9. CCE20003 HGU Pseudo code 1. Given a list of elements, find the smallest element and make it the first element of the list. Let the sub- list except the first element be the remaining list. 2. Given the remaining list, find the smallest element and make it the first element of the remaining list. Make a new remaining list by excluding the first element. 3. Repeat Step 2 until the remaining list becomes a single element.
  • 10. CCE20003 HGU def selection_sort(L): start = 0 end = len(L) while start < end: for i in range(start, end): if L[i] < L[start]: L[start], L[i] = L[i], L[start] start += 1 for the next sub-list return L Finding the smallest one in the current sub-list How about start , end -1 ?
  • 11. CCE20003 HGU BUBBLE SORT Basic idea 1st round Like a bubble floating up! 5 9 4 7 3 5 9 4 3 7 5 9 3 4 7 5 3 9 4 7 3 5 9 4 7 4 comparisons
  • 15. CCE20003 HGU Pseudo code 1.Enumerate a series of sub-lists of a list of elements, each sub-list containing the elements from the i-th one to the last one for i = 0, 1, 2, 3, ……, n-1 2. For each sub-list, scan the sub-list in the reverse order from the end, compare every consecutive pair of elements, and swap the elements, if needed, to make the smaller one float up. 3. Stop when all sub-lists are scanned.
  • 16. CCE20003 HGU def bubble_sort(L): for i in range ( len(L) - 1): for j in range(len(L) - 1 - i): i1 = (len(L)-1) - (j + 1) i2 = (len(L)-1) - j if L[i1] > L[i2]: L[i1], L[i2] = L[i2], L[i1] return L Bubbles float up! Sort a sub-list.
  • 17. CCE20003 HGU RECURSION Recursion is defining something in terms of itself. It sounds a bit odd, but very natural in fact. Here are some examples: According to the legal code of United States, a U.S. citizen is 1. any child born inside United States, or the base case 2. any child born outside United States and at least one of whose parent is a U.S. citizen satisfying certain condition. the recursive(inductive) case
  • 18. CCE20003 HGU In mathematics, the factorial function is defined as follows: f(n) = n X (n-1) X (n-2) X……….X 2 X 1 (n – 1)! f(n – 1) 1 if n = 1 base case n x f(n - 1) if n > 1 recursive case f(n) f(n) =
  • 19. CCE20003 HGU Fibonacci numbers 1 if n = 0 1 if n = 1 f(n – 1) + f(n - 2) f(n) base case recursive case n f(n) 0 1 1 1 2 2 3 3 4 5 5 8 6 13 …… ……
  • 20. CCE20003 HGU Recursive functions A function is said to be recursive if the function is defined in terms of itself, specifically, the function can call itself during its execution.
  • 21. CCE20003 HGU Factorial function 1 if n = 1 base case n x f(n - 1) if n > 1 recursive case f(n) def fact(n): if n == 1: return 1 return n * fact(n-1) def fact(n): result = 1 while n >1: result = result * n n -= 1 return result f(n) =
  • 22. CCE20003 HGU def fact(n): if n == 1: print 1, return 1 else: print n, "x ", return n * fact(n-1) x = fact(7) print “ = “, x 7 x 6 x 5 x 4 x 3 x 2 x 1 = 5040
  • 23. CCE20003 HGU Fibonacci numbers 1 if n = 0 1 if n = 1 f(n – 1) + f(n - 2) f(n) base case recursive case def fib(n): if n == 0 or n == 1: return 1 else: return fib(n – 1) + fib(n - 2) fib(5)
  • 24. CCE20003 HGU def fib(n): global lv lv += 1 if n == 0 or n == 1: print " " * 4 * lv, 1 lv -= 1 return 1 else: print " " * 4 * lv, "fib(", n,")" x = fib(n - 1) + fib(n - 2) lv -= 1 return x lv = -1 x = fib(5) print “n“, ”fib(5) = ", x fib( 5 ) fib( 4 ) fib( 3 ) fib( 2 ) 1 1 1 fib( 2 ) 1 1 fib( 3 ) fib( 2 ) 1 1 1 fib(5) = 8
  • 25. CCE20003 HGU 8 5 3 3 2 2 1 2 1 1 1 1 1 1 1 Fib(5) Fib(4) Fib(3) Fib(3) Fib(2) Fib(2) Fib(2)
  • 26. CCE20003 HGU Palindromes def is_palin(s): if len(s) <= 1: return True else: return (s[0] == s[-1]) and is_palin(s[1, -1]) palin(s) = True if n <= 1 base case (s[0] == s[-1]) and palin(s[1: -1]) if n > 1 recursive case
  • 27. CCE20003 HGU doggod oggo gg True True True True def is_palin(s): global lv lv += 1 if len(s) <= 1: display(True) lv -= 1 return True else: display(s) flag = (s[0] == s[-1]) and is_palin(s[1 : -1]) display(flag) lv -= 1 return flag def display(s): global lv if lv == 0: print s else: print " " * 4 * lv, s lv = -1 is_palin( "dogGod".lower())