--There is an algorithm in the afternoon exam of the Fundamental Information Technology Engineer Examination. I can't understand even if I solve the past questions ... I would like to actually write the algorithm in Python to deepen my understanding.
--Last time, I wrote the algorithm of Maximum array value. --This time, I will write from the algorithm of ** linear search **.
--Extracts the elements of the array in order from the beginning to the end and compares them with the specified value.
#SeqSearch function that finds the value specified by a linear search
def SeqSearch(A,Length,X):
Pos = -1
i = 0
#Iterative processing
while i < Length and Pos == -1: #Means "not reached the end of the array" and "not found"
print("Pos=",Pos,"i=",i,"A[i]=",A[i]) #Results on the way
#Branch processing
if A[i] == X:
Pos = i
i += 1
return Pos
print("Execution result:",SeqSearch([22,55,66,11,44,77,33],7,77))
Pos= -1 i= 0 A[i]= 22
Pos= -1 i= 1 A[i]= 55
Pos= -1 i= 2 A[i]= 66
Pos= -1 i= 3 A[i]= 11
Pos= -1 i= 4 A[i]= 44
Pos= -1 i= 5 A[i]= 77
Execution result: 5
--Linear search is a little complicated --Next time, let's write an algorithm for ** binary search **
--I quoted or referred to Chapter 3 04 Linear Search in this book. Information processing textbook, book that can solve algorithm problems of the Fundamental Information Technology Engineer Examination, 2nd edition
Recommended Posts