|
|
马上注册,结交更多好友,享用更多功能,让你轻松玩转新大榭论坛!
您需要 登录 才可以下载或查看,没有账号?注册
x
线性查找 指按一定的顺序检查数组中每一个元素,直到找到所要寻找的特定值为止。 5 Z3 }0 F0 ?" Q' X, \1 @
7 v- o. m, {. ~
实例- def search(arr, n, x): 2 {) K# T6 R6 R: B0 @5 E
- $ m. @: T! |7 S0 X0 b9 P: Z
- for i in range (0, n):
O' X& g7 X& }! f - if (arr[i] == x): * o1 }0 `7 Y9 i3 W6 E
- return i;
- ~' x$ l$ F8 b - return -1;
( ~3 b4 ?; x$ p -
$ E4 A( \( Y2 c- b( v - # 在数组 arr 中查找字符 D
9 b( ^! k2 X7 s/ K) h% w+ b - arr = [ 'A', 'B', 'C', 'D', 'E' ];
/ Z2 H$ `: Z1 F0 M9 c - x = 'D'; " K! M( y- W7 l8 ?
- n = len(arr); - [3 v; Y8 |) o {+ s, {
- result = search(arr, n, x)
2 F$ |& ]. J x$ _3 c - if(result == -1):
8 H; s: H; a$ C! c - print("元素不在数组中") 4 s. |) M. y- Z: I
- else: 5 {: b) L9 D. @* m) ^
- print("元素在数组中的索引为", result);
复制代码 执行以上代码输出结果为:
' t5 A/ v* Z. d+ n4 h' R. `3 d! X# X4 a9 b& f' L
案例1:- def LinearSearch(list):
6 r$ S3 j; r% M - num = int(input('Number:\t'))
0 A6 {; N v" `6 V& g- N: { - counter = 03 n; P, V8 i3 V6 e* j' g' q! L
- null = 0$ w* p6 W3 O( X6 W2 g. A$ I
- 8 V! x) `2 X+ X( W( @
- for i in list:$ P+ T K5 E2 O
- if i == num: U+ ^. A* \) J7 e: P
- print('Find number {} in place {}.'.format(num, counter))
Q) Z! o% s. n+ ^9 n# O6 t; U - else:
1 \: U1 E' K4 z( ?5 A3 u - null += 1
: r* [2 c2 c" o! s - counter += 17 O# J* H; n* J' z% G8 V* O) ~
- if null == counter:
/ M0 q& o/ p) o' s1 I - print('Don\'t find it.')
7 W9 I# @# u6 M$ c0 U - ) {# i- y" \ j+ z
- list = [1, 2, 5, 7, 8, 34, 567, -1, 0, -1, -3, -9, 0]
. j# J3 a* p% [. b - LinearSearch(list)
复制代码 案例2
, |8 E; T+ V# Z5 p4 L9 s( K- def LinearSearch(num=50):2 J+ m0 z; x! k) X) q# L
- import random
! r( G8 G* w; B. }+ M - random.seed(888)
+ ^6 F `& D3 y0 a" w3 g. A - data = []
( Z& @8 N2 L1 z8 R, O, x H6 S - for i in range(15):
$ B! F- Q# t2 d) ]' U( t5 R( \ - data.append(random.randint(1, 100))
5 k% V$ T S, t% I - data.sort()8 N0 P5 H. ^5 B+ W
- print(data)! X$ |! g. h: ^' Q
- for i in range(0,len(data)):: Z9 V7 K u% ?, e
- if data[i]==num:
2 R0 f# z8 t' g, C - print(i)
6 b: z; n, t7 D! r: ?$ f0 u% X - break
, a6 L d" e9 _. m: z+ \0 x - else:
9 X1 x4 T) f, A0 ^ - print('查无此数'), p( q& S8 k6 y
- LinearSearch()
复制代码
- t8 d& G) Q8 w# E% ]$ n- z, W' p% \ L+ F
|
|