The book I was reading came to the algorithm chapter. Practice of Insert Sort is. Like this Sort the contents of the array in ABC order Sort.
insertion_sort.py
# coding: UTF-8
#Japanese cannot be included in the code without ↑
List = ['Fred', 'Alex', 'Diana', 'Byron', 'Carol' ]
#Insertion method
N = 2 #The insertion method begins with touching the second element
while len(List) >= N: #As long as the value of N does not exceed the length of the List
pip = List[N-1] #Pivot the Nth element, move the contents to a temporary place,
List[N-1] = 'BLANK' #Make it a gap (it is not necessary to specify the gap)
sukima = N-1 #Position of the first gap
while sukima != 0: #As long as "the name is above the gap (= the current gap is the second and subsequent elements)"
if List[sukima-1] > pip: #If "just above the gap is larger than the pivot"
List[sukima] = List[sukima-1] #Drop it in the gap
sukima = sukima-1 #The top is a new gap.
else: break
List[sukima] = pip #Return the pivot to the gap.
N = N + 1 #Increment and repeat processing
#output
for x in List:
print x
On the way, compare the size of the pivot and the string of the element.
I'm not sure what "character string size" means here.
But min (List)
returns Arex and max (List)
returns Fred, so
I presume that the later in the ABC order, the larger the character string.
Result It's fun if it works.
Introduction to Computer Science p218-p222
Recommended Posts