selectionSort
selectionSort
μ ν μ λ ¬ (SelectSort)
: κ°μ₯ μμ κ²μ μ νν΄μ κ³μν΄μ μ μΌ μμΌλ‘ 보λ΄λ μκ³ λ¦¬μ¦
κ°μ₯ μμμ μ΄κ³ κΈ°μ΄μ μΈ λ°©λ² μ€ νλ
λ°μ΄ν°μ κ°―μκ° Nκ°μΌ λ μ΄ λͺλ²μ λΉκ΅ μ°μ°μ ν΄μΌ λλμ§ μμμΌ νλ€.
μ ν μ λ ¬μ λλ΅ N * (N+1)/2 λ² κ°λμ μ°μ°μ μνν΄μΌ νλ€.
μ΄λ₯Ό μ»΄ν¨ν°μμλ κ°μ₯ ν° μ°¨μμΈ N^2λ§ λ³΄κ³ O(N^2)μ΄λΌκ³ νννλ€. μ¦, μ ν μ λ ¬μ μκ° λ³΅μ‘λλ O(N^2)μ΄λ€
μ λ ¬ λ°©λ²

μμ 보λ κ·Έλ¦Όκ³Ό κ°μ΄ step μμλ μμλλ‘ λΉκ΅νλ©° index 0μ κ°μ λμ κ°κΉμ§ λΉκ΅νλ€
κ°κ°μ stepμ κ±°μΉλ©΄μ μννλ©΄μ μ΅μκ°μ μ°Ύμμ μμΉλ₯Ό λ°κΏμ€λ€
Nκ°μ μμμ λν΄μλ N-1λ²μ λΉκ΅νκΈ° λΉκ΅νλ€
public class SelectionSort {
public static void main(String[] args) {
int i, j, temp;
int[] arr = {1, 10, 5, 8, 7, 6, 4, 3, 2, 9};
for(i = 0; i < arr.length-1; i++) {
for (j = i+1; j < arr.length ; j++) {
if (arr[i] > arr[j]) {
temp = arr[i]; // κ°μ₯ μμ μλ κ°μΌλ‘ μμΉ
arr[i] = arr[j]; // κ°μ₯ μμ μλ κ°μ μ΅μκ°μ μμΉ
arr[j] = temp;
}
}
// swap (κ°μ₯ μμ μλ κ°κ³Ό μ΅μκ°μ λ³κ²½)
}
for (i =0 ; i < arr.length; i++) {
System.out.printf("%d ", arr[i]);
}
}
}
def selectionSort(a):
n = len(a)
for i in range(0, n - 1):
min_idx = i
for j in range(i + 1, n):
if a[j] < a[min_idx]:
min_idx = j
a[i], a[min_idx] = a[min_idx], a[i] # swap
print(a) # μ λ ¬ κ³Όμ μΆλ ₯νκΈ°
d = [1, 10, 5, 8, 7, 6, 4, 3, 2, 9]
selectionSort(d)
print(d)
Last updated
Was this helpful?