λ°°μ΄μ λμΌν μ νμ λ°μ΄ν° μμκ° μμλλ‘ μ μ₯λ λ°μ΄ν° ꡬ쑰μ λλ€. κ° μμλ μΈλ±μ€(μΌλ°μ μΌλ‘ 0λΆν° μμ)μ μν΄ μλ³λ©λλ€. λ°°μ΄μ λ°μ΄ν°λ₯Ό ν¨μ¨μ μΌλ‘ μ μ₯νκ³ κ²μνλ λ° μ¬μ©λ©λλ€.
μΈλ±μ€(Index): λ°°μ΄μ κ° μμλ κ³ μ ν μΈλ±μ€λ‘ μλ³λ©λλ€. μΌλ°μ μΌλ‘ 0λΆν° μμνμ¬ λ°°μ΄μ κΈΈμ΄λ³΄λ€ νλ μμ κ°κΉμ§μ λ²μλ₯Ό κ°μ΅λλ€.
κΈΈμ΄(Length): λ°°μ΄μ κΈΈμ΄λ λ°°μ΄μ ν¬ν¨λ μμμ μλ₯Ό λνλ
λλ€. μλ₯Ό λ€μ΄, κΈΈμ΄κ° 7μΈ λ°°μ΄μ 0λΆν° 6κΉμ§μ μΈλ±μ€λ₯Ό κ°λ μΌ κ°μ μμλ‘ κ΅¬μ±λ©λλ€.
μ ν(Type): λ°°μ΄μ λμΌν μ νμ λ°μ΄ν° μμλ‘ κ΅¬μ±λλ©°, μλ₯Ό λ€μ΄ μ μ, λ¬Έμμ΄, λΆλ μμμ μ λ±μ΄ λ μ μμ΅λλ€.
μ μΈ λ° μ΄κΈ°ν(Declaration and Initialization)
Linear search(μ ν κ²μ)
Linear search(μ ν κ²μ)λ λ°°μ΄μμ νΉμ κ°μ μ°Ύλ κ°λ¨νλ©΄μλ μ§κ΄μ μΈ κ²μ μκ³ λ¦¬μ¦ μ€ νλμ λλ€. Linear searchλ λ°°μ΄μ μ²μλΆν° λκΉμ§ μμ°¨μ μΌλ‘ κ° μμλ₯Ό κ²μ¬νλ©΄μ μ°Ύκ³ μ νλ κ°μ μ°Ύμ λκΉμ§ λ°λ³΅ν©λλ€.
public static int linearSearch(int[] array, int target) {
for (int i = 0; i < array.length; i++) {
if (array[i] == target) {
return i; // μ°Ύμ κ²½μ° ν΄λΉ μμμ μΈλ±μ€ λ°ν
}
}
return -1; // μ°Ύμ§ λͺ»ν κ²½μ° -1 λ°ν
}
public static void main(String[] args) {
int[] myArray = {10, 20, 30, 40, 50};
int targetValue = 30;
int result = linearSearch(myArray, targetValue);
if (result != -1) {
System.out.println("κ° " + targetValue + "μ λ°°μ΄μ μΈλ±μ€ " + result + "μ μμΉν΄ μμ΅λλ€.");
} else {
System.out.println("κ° " + targetValue + "μ μ°Ύμ μ μμ΅λλ€.");
}
}
}
μ΄ μμμμλ linearSearch λ©μλλ₯Ό μ¬μ©νμ¬ λ°°μ΄μμ νΉμ κ°(targetValue)μ μ°Ύκ³ , μ°Ύμ κ²½μ° ν΄λΉ κ°μ μΈλ±μ€λ₯Ό λ°ννκ³ , μ°Ύμ§ λͺ»ν κ²½μ° -1μ λ°ννλλ‘ νμ΅λλ€.
Linear searchμ μκ° λ³΅μ‘λλ O(n)μ
λλ€. λ°°μ΄μ ν¬κΈ°κ° nμΌ λ, μ΅μ
μ κ²½μ°μλ nλ²μ λΉκ΅κ° νμνκ² λ©λλ€. λ°λΌμ Linear searchλ μμ ν¬κΈ°μ λ°°μ΄μ΄λ μ λ ¬λμ§ μμ λ°°μ΄μμ μ¬μ©λ μ μμ΅λλ€. ν¬κΈ°κ° ν¬κ±°λ μ λ ¬λ λ°°μ΄μμλ μ΄μ§ κ²μκ³Ό κ°μ λ€λ₯Έ μκ³ λ¦¬μ¦μ΄ λ ν¨μ¨μ μΌ μ μμ΅λλ€.
An array is a data structure that stores elements of the same type in a sequential order, identified by indices.
Linear search is a basic search algorithm that looks for a specific value by checking each element in a collection one by one until a match is found.
'Programming > Java' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
10 Object-Oriented Programming (feat. Procedural Programming) (1) | 2024.01.19 |
---|---|
9 Two-dimensional Arrays (Feat. Object Array) (0) | 2024.01.19 |
7 while loop (feat. do-while) (0) | 2024.01.07 |
6 for loop (feat. Nested, foreach) (0) | 2024.01.07 |
5 If & Switch (feat. break, continue) (0) | 2024.01.07 |
λκΈ