|
|
马上注册,结交更多好友,享用更多功能,让你轻松玩转新大榭论坛!
您需要 登录 才可以下载或查看,没有账号?注册
x
线性查找 指按一定的顺序检查数组中每一个元素,直到找到所要寻找的特定值为止。 4 G- ^/ b; @" O( X+ y
) l: K5 F$ E! q- {8 @& V; v' G. c: v实例- def search(arr, n, x):
: ]6 `$ d4 s1 j3 }- v; \ -
9 ] c, n! I% `2 V+ k - for i in range (0, n): / q! n5 E1 O! V" G
- if (arr[i] == x):
2 {3 J, }* x: y# f( E - return i;
2 z5 K# ^% A+ M; n% D' \ - return -1;
# S- F- |( O2 K N! g - 8 a6 q' T+ {* ]* q$ ~7 v8 x
- # 在数组 arr 中查找字符 D6 ^7 V7 w9 E, v6 L
- arr = [ 'A', 'B', 'C', 'D', 'E' ]; + @1 N( N& Q! E
- x = 'D';
0 n% C6 ^$ g% Z# ]0 b2 G - n = len(arr);
( Y0 J; r" C0 L, S/ }2 s7 Q9 n - result = search(arr, n, x)
( ^+ d y" d* S6 i q - if(result == -1):
$ t N* c- J: e! I! [ z* V - print("元素不在数组中") 9 }/ E7 Z( |+ \& y
- else:
, G" f+ {4 P# z/ [ - print("元素在数组中的索引为", result);
复制代码 执行以上代码输出结果为:; j0 R' N5 _" U- q0 b
% b: R. E' N6 ]' N5 ]案例1:- def LinearSearch(list):& _. D. f9 ^' y
- num = int(input('Number:\t'))
+ d* Z1 g" x& `* q* q - counter = 0. i5 b1 F, E9 Y2 Q' K
- null = 0! D9 m/ X/ K& I8 w* e& X
, C1 J0 T: g' o. p e7 m( H- for i in list:
3 z( ?$ ?8 U5 n3 k& f! N* { c - if i == num:
, @1 ^* X4 }4 g+ L( \1 A - print('Find number {} in place {}.'.format(num, counter))4 i2 g$ v# @8 Z# N; I
- else: O- e0 c Q" ^2 T
- null += 1
3 I, f0 V. x+ Y9 R' h - counter += 1
" @( W/ Z0 R D, L6 t! n) J Z - if null == counter:4 {5 o6 n: {$ e( \
- print('Don\'t find it.')
3 }& w* p \3 T9 \4 d! x3 a - * q5 U2 B6 }6 |( C, `+ C& h# b
- list = [1, 2, 5, 7, 8, 34, 567, -1, 0, -1, -3, -9, 0]$ n' U$ B* F3 S: G/ _
- LinearSearch(list)
复制代码 案例20 |5 y( @6 |+ m" X1 _
- def LinearSearch(num=50):
: F; p! O, G7 q0 n: C - import random# q4 ?& q. j$ W3 M# }4 R
- random.seed(888)
% v8 \' U# r; }% D - data = []
* i A: t ~# o - for i in range(15):
+ C) {1 r, j1 ~ - data.append(random.randint(1, 100))$ y A2 c3 g9 T# |' J* i8 Q( e8 k
- data.sort()
3 I9 [ F7 N* D4 ^ - print(data)2 \2 ?. v d: p+ ~
- for i in range(0,len(data)):" `/ ^* P5 k7 [/ b# x. g6 l
- if data[i]==num:
' [1 h& r& U8 B# W9 o; U - print(i)
2 B! l9 a7 v3 Y - break& U& }9 Q& l$ H9 _" H+ Y2 i
- else:
- H; n3 x1 b2 K# b6 e$ U - print('查无此数')
0 j* h D% U, h( f9 ], F1 m/ r$ q - LinearSearch()
复制代码
/ P+ ~, P" z7 h% L8 k# o2 U1 |: I1 x! H# ]! A
|
|