|
|
马上注册,结交更多好友,享用更多功能,让你轻松玩转新大榭论坛!
您需要 登录 才可以下载或查看,没有账号?注册
x
线性查找 指按一定的顺序检查数组中每一个元素,直到找到所要寻找的特定值为止。 # P1 g3 G# S8 _3 l. C7 Y1 O, s
$ a. }/ p* S% n5 x实例- def search(arr, n, x): 3 \4 W/ C( j$ c: Z' a& E
- 3 A5 m+ t: ~5 E" U1 t* d3 E
- for i in range (0, n): 4 u* A, j% A/ I9 d2 M
- if (arr[i] == x): & j8 \0 v+ o5 c
- return i;
! ^; `" ^& R D! X6 I+ E7 V+ e - return -1;
3 H0 J' i: P/ V. u9 A% n* d# O: W -
/ @- P5 G3 u2 _ D7 c; P/ e1 ? - # 在数组 arr 中查找字符 D
# Q; w! y, @* n3 w- W - arr = [ 'A', 'B', 'C', 'D', 'E' ];
# B$ o `$ s+ @7 ~! o2 o" d - x = 'D'; ; J9 X6 B' _& P3 Y
- n = len(arr);
9 O* H. V* O8 L; C, e - result = search(arr, n, x) % s9 l, X- m/ |
- if(result == -1): 9 I7 G5 B1 Q1 t% k! T: R
- print("元素不在数组中")
4 ~5 u! D9 Z/ b6 z+ K7 } - else: $ h2 z4 _* y3 N9 Q, @( K: G
- print("元素在数组中的索引为", result);
复制代码 执行以上代码输出结果为:( K8 ?$ O) h% f8 N' }' e
& e- l1 d, R7 u9 ~, P
案例1:- def LinearSearch(list):5 ?" |! B: e; z7 M/ q& x
- num = int(input('Number:\t'))
7 U! t7 i' z7 B2 G. P8 y8 _ - counter = 0& Z, m p$ o# W' {5 q
- null = 0
& y D4 |7 s& V" l, q; F4 x/ @
: ` ?' ^# c. r* x- for i in list:
0 |3 \+ C9 q& `/ h' z$ v8 T+ m - if i == num:
^4 ?9 p& i9 |( v. l* ]# N - print('Find number {} in place {}.'.format(num, counter)). r; ~- T( W( c8 [, v8 \0 A2 _5 X$ [
- else:
" v! R/ p/ r Q& A" v - null += 1
0 z& B( P1 N4 B7 V - counter += 18 i9 B1 A2 C- m5 s
- if null == counter:) `6 a8 R# A" W
- print('Don\'t find it.')
2 {. n( x4 S7 f# V, d& i7 f9 b - # V$ v7 [1 g; H. V
- list = [1, 2, 5, 7, 8, 34, 567, -1, 0, -1, -3, -9, 0]
1 T7 k* _5 X& O - LinearSearch(list)
复制代码 案例21 c& A7 |5 X' k X$ w% \
- def LinearSearch(num=50):; ~0 {; k: a6 U E* H+ L- ?
- import random( q* Z' b( a( G: u
- random.seed(888)4 l, H3 D( n) V6 s
- data = []8 Y# r6 ]2 E Z5 ]- o
- for i in range(15):
, R; o T$ j4 U3 X. R: d - data.append(random.randint(1, 100)), G6 n( }% C& W+ Z3 w3 H
- data.sort()1 d3 B# r. A$ v7 f' q) A$ a4 d
- print(data)) H) K# |3 x4 M4 l0 X( W8 e) l; ]: u
- for i in range(0,len(data)):
) t5 x# n4 @' H- z - if data[i]==num:
3 f* @5 I3 e* W( g/ t& @" e* g$ f - print(i)
: P# Z0 k) V* z* s) X - break
" p( ?1 ^9 x4 @9 ^7 I! W; V" s - else:: `8 s/ P3 Q% i N9 G
- print('查无此数')
6 @2 t+ i0 e6 C( {6 ^ - LinearSearch()
复制代码 $ t" Z8 ~$ u6 f4 T+ ^7 F4 I: D. w
0 _/ a3 c4 f1 }) Z# S
|
|