컴공생의 다이어리

[알고리즘] 선택 정렬(Selection Sort) 본문

Development/Algorithm & Coding Test

[알고리즘] 선택 정렬(Selection Sort)

컴공 K 2021. 10. 16. 00:01
728x90

선택 정렬(Selection Sort)

선택 정렬은 버블 정렬(Bubble Sort)과 유사한 알고리즘이다. 해당 순서에 원소를 넣을 위치는 이미 정해져 있고, 어떤 원소를 넣을지 선택하는 알고리즘이다.

 

 

정렬 과정

1. 우선, 위치(index)를 선택한다.

2. i+1번째 원소부터 선택한 위치(index)의 값과 비교를 시작

3. 오름차순이므로 현재 선택한 자리에 있는 값보다 순회하고 있는 값이 작다면, 위치(index)를 갱신

4. 2번 반복문이 끝난 뒤에는 min_index에 1번에서 선택한 위치(index)에 들어가야 하는 값의 위치(index)를 갖고 있으므로 서로 교환(swap)

 

 

파이썬 코드

def selection_sort(arr):
  for i in range(len(arr)-1):
    min_index = i
    for j in range(i+1,len(arr)):
      if(arr[j]<arr[min_index]):
        min_index = j
    arr[min_index],arr[i] = arr[i],arr[min_index]
  return arr

print(selection_sort([5,3,7,9,1]))
# 1, 3, 5, 7, 9

 

 

 

https://gyoogle.dev/blog/algorithm/Selection%20Sort.html

 

선택 정렬(Selection Sort) | 👨🏻‍💻 Tech Interview

선택 정렬(Selection Sort) Goal Selection Sort에 대해 설명할 수 있다. Selection Sort 과정에 대해 설명할 수 있다. Selection Sort을 구현할 수 있다. Selection Sort의 시간복잡도와 공간복잡도를 계산할 수 있다. Ab

gyoogle.dev

https://devuna.tistory.com/28

 

[정렬] 선택정렬(Selection Sort)의 개념/Java코드/시간복잡도/공간복잡도

[정렬] 선택정렬(Selection Sort)의 개념/Java코드/시간복잡도/공간복잡도 📌선택정렬의 개념 선택정렬(Selection Sort)은 해당 순서에 원소를 넣을 위치는 이미 정해져 있고, 그 위치에 어떤 원소를

devuna.tistory.com

 

728x90
반응형
Comments