Algorithm_Java
선형 검색
dhfkdlsj
2024. 6. 23. 22:12
내가 원하는 값을 찾을때까지 배열의 제일 앞에서부터 순서대로 검색하는 것
정렬이 되어있지 않은 배열에서 검색할 때 사용하면 좋다
public class Linear_Search {
public static void main(String[] args) {
int arr[] = {1,2,3,4,5,6,7};
int q = 3; //q가 3일때
boolean b = false;
for(int i:arr){
if (i == q){
System.out.println("찾았습니다.");
b = true;
}
}
if (!b)
System.out.println("못찾았습니다.");
}
}
// 실행 결과
찾았습니다.
public class Linear_Search {
public static void main(String[] args) {
int arr[] = {1,2,3,4,5,6,7};
int q = 10; //q가 10일때
boolean b = false;
for(int i:arr){
if (i == q){
System.out.println("찾았습니다.");
b = true;
}
}
if (!b)
System.out.println("못찾았습니다.");
}
}
// 실행 결과
못찾았습니다.