|
|
马上注册,结交更多好友,享用更多功能,让你轻松玩转新大榭论坛!
您需要 登录 才可以下载或查看,没有账号?注册
x
线性查找 指按一定的顺序检查数组中每一个元素,直到找到所要寻找的特定值为止。
1 n) c2 ]# K7 L) c' N* B. m5 C
2 y9 g$ ~0 j$ [
实例- def search(arr, n, x):
% Z% i6 {" N, G# O - 6 x6 A; i8 x0 s/ F
- for i in range (0, n): 9 l" {* t& F% \. ^: j5 c
- if (arr[i] == x):
* B4 ~. [+ @ ~* |$ y8 }, h - return i;
0 m8 s. h q E - return -1;
# I2 O. R- m4 z7 k: R) ` - 8 {- L6 }: V H, x) e8 J0 M( c2 i
- # 在数组 arr 中查找字符 D( B2 P* L/ |' O
- arr = [ 'A', 'B', 'C', 'D', 'E' ]; % U k" ]8 u9 _
- x = 'D';
' O- j& F, z* |& B: D; w% k! q - n = len(arr); 4 Q5 v) T$ J/ Z+ _9 q# ]7 t% [4 R4 l
- result = search(arr, n, x) % [! U* n, y# s
- if(result == -1): ! Z1 A% h% {& Q
- print("元素不在数组中") . g5 J, d% F% |
- else: ( I) R; b( ~' i1 M! l5 O
- print("元素在数组中的索引为", result);
复制代码 执行以上代码输出结果为:
- [/ }9 t% u$ L" T( Z( [8 d; y
) u( m5 | I+ W8 n( a案例1:- def LinearSearch(list):) Y* h9 p6 @0 [$ a
- num = int(input('Number:\t'))
X" J) S. W# Q, s+ w! j( \ - counter = 0
: Z) |% _' q2 w7 ^# S - null = 0
# R0 B8 V' i1 W) t8 A5 U
- f$ m+ [& \& v0 m5 L. W! j- for i in list:4 [& G# z4 ~4 h* x1 u* P& z
- if i == num:
* T9 k( }& t7 |( h - print('Find number {} in place {}.'.format(num, counter))2 L; X& f4 n+ c1 f9 v' T
- else:
) D s* U# F+ d- r) d+ w) A - null += 1. h% \' c1 S( g* S9 X
- counter += 1
8 L) o" a; k9 l* t' ]$ K - if null == counter:
: ^8 R, A" G: O4 H9 k6 g8 z - print('Don\'t find it.'); ~8 [ C2 A6 b. D6 k4 b; ]
- : X1 s+ u1 L' t* d2 p8 }1 I
- list = [1, 2, 5, 7, 8, 34, 567, -1, 0, -1, -3, -9, 0]
/ n2 ]! A; A7 z7 N: t - LinearSearch(list)
复制代码 案例2 M# ]: G2 O* z3 E
- def LinearSearch(num=50):) e7 M9 @& x) }' b+ h9 j% y/ v. r* ~
- import random O* e- j# n" V e
- random.seed(888)
5 t+ A: ]3 ^$ U6 O+ t - data = []
2 D" m; G+ W7 `& F* J - for i in range(15):
6 u5 x" X6 a7 O$ V: z* u" H - data.append(random.randint(1, 100))1 ?0 Z; ?* s3 E
- data.sort()3 C2 k( T7 \9 K& T
- print(data)
6 [ Q; @. ]6 [; a* V8 n6 H - for i in range(0,len(data)):7 S) R, H- [7 Y) t, ]% r9 w* D
- if data[i]==num: @: J+ j9 V! q9 D, x+ e
- print(i)$ {6 P" _$ b0 |* k( r
- break( ?7 V. N2 @" [+ T
- else:9 M1 K4 t( J, @9 S* F( K
- print('查无此数')
4 y l( G$ j, s7 v- ~6 U; n& W - LinearSearch()
复制代码
; L1 ?# c8 i" @( `* d8 W3 w/ A7 O7 H# x" c& W. k
|
|