-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSeqSearch.java
More file actions
42 lines (33 loc) · 859 Bytes
/
SeqSearch.java
File metadata and controls
42 lines (33 loc) · 859 Bytes
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
package org.doit;
import java.util.Scanner;
/*
*
선형 검색
*
*/
public class SeqSearch {
// 요솟수가 n인 배열 a에서 key와 같은 요소를 선형 검색합니다.
static int seqSearch(int[] a, int n, int key) {
for (int i=0; i<n; i++) {
if (a[i] == key) return i;
}
return -1;
}
public static void main(String[] args) {
Scanner std = new Scanner(System.in);
System.out.println("요솟수 : ");
int num = std.nextInt();
int[] x = new int[num];
for (int i=0; i<num; i++) {
System.out.print("x[" + i +"] : ");
x[i] = std.nextInt();
}
System.out.println("검색할 값 : ");
int ky = std.nextInt();
int idx = seqSearch(x, num, ky);
if(idx == -1)
System.out.println("검색값을 찾지 못했습니다.");
else
System.out.println(ky + "는 x[" + idx + "]에 있습니다.");
}
}