a)原理:順序查找就是按順序從頭到尾依次往下查找,找到數(shù)據(jù),則提前結束查找,找不到便一直查找下去,直到數(shù)據(jù)最后一位。
b)圖例說明: 原始數(shù)據(jù):int[]a={4,6,2,8,1,9,0,3}; 要查找數(shù)字:8

找到數(shù)組中存在數(shù)據(jù)8,返回位置。
代碼演示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
import java.util.Scanner; /* * 順序查找 */ public class SequelSearch { public static void main(String[] arg) { int [] a={ 4 , 6 , 2 , 8 , 1 , 9 , 0 , 3 }; Scanner input= new Scanner(System.in); System.out.println( "請輸入你要查找的數(shù):" ); //存放控制臺輸入的語句 int num=input.nextInt(); //調(diào)用searc()方法,將返回值保存在result中 int result=search(a, num); if (result==- 1 ){ System.out.println( "你輸入的數(shù)不存在與數(shù)組中。" ); } else System.out.println( "你輸入的數(shù)字存在,在數(shù)組中的位置是第:" +(result+ 1 )+ "個" ); } //順序排序算法 public static int search( int [] a, int num) { for ( int i = 0 ; i < a.length; i++) { if (a[i] == num){ //如果數(shù)據(jù)存在 return i; //返回數(shù)據(jù)所在的下標,也就是位置 } } return - 1 ; //不存在的話返回-1 } } |
運行截圖:
