selectionSort

selectionSort

선택 μ •λ ¬ (SelectSort)

: κ°€μž₯ μž‘μ€ 것을 μ„ νƒν•΄μ„œ κ³„μ†ν•΄μ„œ 제일 μ•žμœΌλ‘œ λ³΄λ‚΄λŠ” μ•Œκ³ λ¦¬μ¦˜

  • κ°€μž₯ μ›μ‹œμ μ΄κ³  기초적인 방법 쀑 ν•˜λ‚˜

  • λ°μ΄ν„°μ˜ κ°―μˆ˜κ°€ N개일 λ•Œ 총 λͺ‡λ²ˆμ˜ 비ꡐ 연산을 ν•΄μ•Ό λ˜λŠ”μ§€ μ•Œμ•„μ•Ό ν•œλ‹€.

  • 선택 정렬은 λŒ€λž΅ N * (N+1)/2 번 κ°€λŸ‰μ˜ 연산을 μˆ˜ν–‰ν•΄μ•Ό ν•œλ‹€.

  • 이λ₯Ό μ»΄ν“¨ν„°μ—μ„œλŠ” κ°€μž₯ 큰 차수인 N^2만 보고 O(N^2)이라고 ν‘œν˜„ν•œλ‹€. 즉, 선택 μ •λ ¬μ˜ μ‹œκ°„ λ³΅μž‘λ„λŠ” O(N^2)이닀

μ •λ ¬ 방법

selectionSort
  • μœ„μ— λ³΄λŠ” κ·Έλ¦Όκ³Ό 같이 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?