|
|
马上注册,结交更多好友,享用更多功能,让你轻松玩转新大榭论坛!
您需要 登录 才可以下载或查看,没有账号?注册
x
线性查找 指按一定的顺序检查数组中每一个元素,直到找到所要寻找的特定值为止。 7 c7 L* D' c4 R- q$ w- |" M& n( Y
) I9 B$ _6 w; @
实例- def search(arr, n, x):
! c. P! ?, M5 j1 a3 ^# B6 k -
D" S3 S+ [+ y6 Y E0 o, x - for i in range (0, n): V$ t6 w' Z9 v5 M
- if (arr[i] == x):
/ z# B3 O' o3 ?8 E - return i; 5 p# g. f* I# m' e
- return -1;
: V0 ?: P; e4 E6 W2 {- f( [" S - 1 t1 N9 J% V9 k+ J2 J
- # 在数组 arr 中查找字符 D
- ]8 Z% [7 [2 p* W _ - arr = [ 'A', 'B', 'C', 'D', 'E' ]; 9 }+ f9 Q- x( B# U* }( ^+ i3 d* O
- x = 'D';
; ~* Y! R- ]( ?7 j! V% Y1 u - n = len(arr); ; {0 |* b, T$ W6 l5 t* I$ |# w
- result = search(arr, n, x) 8 o5 f5 |7 y) O+ C5 a# j! @
- if(result == -1): 7 u8 Q5 r1 s7 y! U
- print("元素不在数组中") % S- X+ y2 Y' B' g4 ~
- else: 6 l' C) b! w6 J- w5 [8 j
- print("元素在数组中的索引为", result);
复制代码 执行以上代码输出结果为:; c6 o% ]- n' x5 p+ t
: w; L- G4 Y7 p. B. h J' k
案例1:- def LinearSearch(list):
8 M* D9 N& N' B5 [& Z5 r! f - num = int(input('Number:\t'))
( I h0 ]' z1 S2 E* t - counter = 0/ d6 t! T7 D$ E8 `
- null = 0& G! s& C% T% w y/ c, G
- / R/ @( _9 {- R! W
- for i in list:) D3 O/ k1 u9 V+ @' L! X
- if i == num:2 H0 {) w6 l9 x
- print('Find number {} in place {}.'.format(num, counter))1 \ G/ C7 |0 N6 Z, j+ |
- else:
, Z- C6 [/ N% v" P/ I - null += 1- D- B- T- i1 O: Q
- counter += 1. c. M% i0 ]! W/ f
- if null == counter:
/ a( o, e8 U( |; \9 o - print('Don\'t find it.')) {3 X9 U/ U# Z2 h
* }2 V# `, X/ N% s! A- list = [1, 2, 5, 7, 8, 34, 567, -1, 0, -1, -3, -9, 0]
. V4 Q" R5 v. h3 [; }4 M2 b. k - LinearSearch(list)
复制代码 案例2
# U% O! g8 U) K W3 A* b3 U' B- def LinearSearch(num=50):
$ c0 s' M: Z8 R! ]* N - import random
# T/ n3 L) `0 R2 e - random.seed(888)
; d) `1 K9 n0 K) ~, @ - data = []
0 H! T# x& ^: Y - for i in range(15):
0 j( ^+ o5 m$ Z. f+ W. j - data.append(random.randint(1, 100))
- b' p" B) V x# n1 h - data.sort()
6 c: w" X u$ N$ ` j8 N* S - print(data)
|- q7 D1 O) O' c - for i in range(0,len(data)):
( S7 P8 v& t! f3 J3 T - if data[i]==num:( v* a. s7 |% K$ A% J
- print(i)
4 z2 u8 ~* {* O" Z3 s - break
! _* P% l3 T0 b" A' n6 f - else:1 Y) A; u) d" ]% m5 a: `6 i/ }
- print('查无此数')
0 \( U6 @( s* R: f/ P' D' H8 a - LinearSearch()
复制代码 , V5 d0 ~+ f4 J/ C4 ]# {
) V1 E1 m+ e. ?8 @2 o( R: N |
|