-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSeqSearch.java
More file actions
45 lines (34 loc) · 1.06 KB
/
Copy pathSeqSearch.java
File metadata and controls
45 lines (34 loc) · 1.06 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 SeqSearch {
// 요솟수가 n인 배열 a에서 key와 같은 요소를 선형 검색
static int seqSearch(int[] a, int n, int key) {
int i=0;
while(true) {
if(i == n)
return -1; // 검색 실패(-1을 반환)
if(a[i] == key)
return i; // 검색 성공(인덱스 반환)
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]; // 요솟수가 num인 배열
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 = seqSearch(x, num, ky); // 배열 x에서 키 값이 ky인 요소를 검색
if(idx == -1)
System.out.println("그 값의 요소가 없습니다.");
else
System.out.println(ky + "은(는) x[" + idx + "]에 있습니다.");
stdIn.close();
}
}