Python and Data Structures
Tyler Moore
CSE 3353, SMU, Dallas, TX
January 31, 2013
These slides have been adapted from the slides written by Prof. Steven Skiena at SUNY Stony Brook, author of Algorithm Design Manual. For more information see http://www.cs.sunysb.edu/~skiena/
Problem of the Day
1 Install Python on your computer 2 Write Python code to implement an insertion sort. You may refer to
the C code on p. 4 of the ADM You may also refer to the Python code implementing selection sort at http://lyle.smu.edu/~tylerm/courses/cse3353/code/l3.zip Submit the code via Blackboard
2 / 32
Insertion Sort (C)
1
i n s e r t i o n s o r t ( int s [ ] , int n)
2
{
3
int i , j ;
4
int min ;
5
for ( i =1; i <n ; i++) {
6
j = i ;
7
while (( j >0) &&
8
( s [ j ] < s [ j −1])) {
9
swap(&s [ j ] ,& s [ j −1]);
10
j = j −1;
11
}
12
}
13
}
3 / 32
Insertion Sort (Python)
1 def
i n s e r t i o n s o r t ( s ) :
2
”””
3
Input : l i s t s to be s o r t e d
4
Output : s o r t e d l i s t
5
”””
6
for i in range ( l e n ( s ) ) :
7
j=i #don ’ t c a l l v a r i a b l e min s i n c e i t ’ s r e s e r v e d word
8
while j >0 and s [ j ]<s [ j −1]:
9
s [ j ] , s [ j −1]=s [ j −1] , s [ j ]
10
j=j −1
11
return s
4 / 32