When the different data structures, the search data storage very basic necessary conditions. The easiest way is to traverse the data structure of each element, and match it with the value you are searching for. This is called linear search. It is inefficient, rarely used, but to create a program for it shows how we implement some of the ideas advanced search algorithm.
Linear search
in this type of search, searching all values one by one. Each value will be checked, if a match is found, then return the specified value, otherwise the search will continue until the end of the data structure. code show as below:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
|
def
linear_search(data, search_for):
"""线性搜索"""
search_at
=
0
search_res
=
False
while
search_at <
len
(data)
and
search_res
is
False
:
if
data[search_at]
=
=
search_for:
search_res
=
True
else
:
search_at
+
=
1
return
search_res
lis
=
[
5
,
10
,
7
,
35
,
12
,
26
,
41
]
print
(linear_search(lis,
12
))
print
(linear_search(lis,
6
))
|
Interpolation search
of the search algorithm is applied to the desired value of the probe position. In order for this algorithm to work, in the form of data collection should be sorted and distributed evenly. Initially, the probe position is the position of the largest items in the collection. If a match occurs, the index of the item is returned. If the item is greater than the intermediate items, the recalculated position of the probe in the middle of the right subarray project. Otherwise, the program will search in the middle of the left side of the array of sub-projects. This process continues on the sub-array, the array size until the child is reduced to zero. code show as below:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
|
def
insert_search(data,x):
"""插值搜索"""
idx0
=
0
idxn
=
(
len
(data)
-
1
)
while
idx0 <
=
idxn
and
x >
=
data[idx0]
and
x <
=
data[idxn]:
mid
=
idx0
+
int
(((
float
(idxn
-
idx0)
/
(data[idxn]
-
data[idx0]))
*
(x
-
data[idx0])))
if
data[mid]
=
=
x:
return
"在下标为"
+
str
(mid)
+
"的位置找到了"
+
str
(x)
if
data[mid] < x:
idx0
=
mid
+
1
return
"没有搜索到"
+
str
(x)
lis
=
[
2
,
6
,
11
,
19
,
27
,
31
,
45
,
121
]
print
(insert_search(lis,
31
))
print
(insert_search(lis,
3
))
|