-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSeqSearchSen.java
More file actions
45 lines (34 loc) · 1.11 KB
/
Copy pathSeqSearchSen.java
File metadata and controls
45 lines (34 loc) · 1.11 KB
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
package search;
import java.util.Scanner;
// 선형 검색(보초법) = 검색하고자 하는 키 값을 맨 끝 요소에 지정한다
public class SeqSearchSen {
// 요솟수가 n인 배열 a에서 key와 같은 요소를 보초법으로 선형 검색
static int seqSearchSen(int[] a, int n, int key) {
int i = 0;
a[n] = key; // 보초를 추가
while (true) {
if (a[i] == key) // 검색 성공
break;
i++;
}
return i == n ? -1 : i;
}
public static void main(String[] args) {
Scanner stdIn = new Scanner(System.in);
System.out.print("요솟수 : ");
int num = stdIn.nextInt();
int[] x = new int[num+1]; // 요솟수 num + 1
for(int i=0; i<num; i++) {
System.out.print("x[" + i + "] :");
x[i] = stdIn.nextInt();
}
System.out.print("검색할 값 : "); // 키 값을 입력
int ky = stdIn.nextInt();
int idx = seqSearchSen(x, num, ky); // 배열 x에서 값이 ky인 요소를 검색
if(idx == -1)
System.out.println("그 값의 요소가 없습니다.");
else
System.out.println(ky + "은(는) x[" + idx + "]에 있습니다.");
stdIn.close();
}
}