728x90
반응형
SMALL
요소가 잭선 모양으로 늘어선 배열에서의 검색은 워하는 키 값을 갖는 요소를 만날 때까지 맨앞부터순서대로 요소를 검색하는 방식을 선형 검색(Linear Search) 또는 순차 검색(Sequential Search)이라는 알고리즘 입니다.
//선형검색
public class SeqSearchFor {
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 scanner = new Scanner(System.in);
System.out.print("요소수 : ");
int num = scanner.nextInt();
int[] x = new int[num];
for(int i = 0; i < num; i++){
System.out.print("x["+i+"] = ");
x[i] = scanner.nextInt();
}
System.out.print("검색할 값 : ");
int ky = scanner.nextInt();
int idx = seqSearch(x, num, ky); //배열 x에서 키값이 ky인 요소를 검색
if(idx == -1) System.out.println("그 값의 요소가 없습니다.");
else System.out.println(ky+"는 x["+idx+"]에 있습니다.");
}
}
실행결과
요소수 : 3
x[0] = 1
x[1] = 2
x[2] = 3
검색할 값 : 3
3는 x[2]에 있습니다.
728x90
반응형
LIST
'Algorithm' 카테고리의 다른 글
[Algorithm] 이진 검색 (1) | 2023.12.08 |
---|---|
[Algorithm] 보초법 (0) | 2023.12.08 |
[Algorithm] 기수 변환 (0) | 2023.12.06 |
[Algorithm] 배열 모든 요소 합계 (1) | 2023.12.05 |
[Algorithm] 배열 역순 정렬 (1) | 2023.12.05 |