일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 | 31 |
- 함수형 코딩
- git
- algorithms
- 2020년 제4회 정보처리기사 필기 문제 분석
- java
- sqldeveloper
- 항해99
- Real MySQL
- jsp
- 성적프로그램
- 2020년 정보처리기사 4회
- 2020년 일정
- 필기
- post
- hackerrank
- 코드숨
- 회고
- 주간회고
- 정보처리기사
- 책리뷰
- LeetCode
- 미니프로젝트
- 스터디
- 알고리즘
- 서평
- 뇌정리
- Jackson
- Python
- If
- Til
- Today
- Total
조컴퓨터
선택 정렬(selection sort) 본문
1) 선택 정렬(selection sort) 이란?
다음과 같은 순서를 반복하며 정렬하는 알고리즘
- 주어진 데이터 중에서 최소값을 찾음
- 해당 최소값을 데이터 제일 앞에 위치한 값과 교체함
- 제일 앞의 위치를 뺀 나머지 데이터를 동일한 방법으로 반복하여 교체함
2) 알고리즘 구현
▼ 파이썬
def selection_sort(data):
for stand in range(len(data) - 1):
lowest = stand
for idx in range(stand + 1, len(data)):
if data[lowest] > data[idx]:
lowest = idx
data[lowest], data[stand] = data[stand], data[lowest]
return data
1. for stand in range(len(data) - 1) 로 반복
2. lowest = stand 로 놓고
3. for idx in range(stand + 1, len(data)) 로 반복 (stand + 1 이후부터 반복)
4. 내부 반복문 안에서 data[lowest] > data[idx] 이면, lowest = idx
5. data[lowest] 와 data[stand] 자리 바꿈
결과
import random
data = random.sample(range(100), 10)
print(selection_sort(data))
▼ 자바
void selectionSort(int[] arr) {
int idxMin, tmp;
for(int i = 0; i < arr.length - 1; i++) { // 1.
idxMin = i;
for(int j = i + 1; j < arr.length; j++) { // 2.
if(arr[j] < arr[idxMin]) { // 3.
idxMin = j;
}
}
// 4. swap (arr[idxMin], arr[i]
tmp = arr[idxMin];
arr[idxMin] = arr[i];
arr[i] = tmp;
}
System.out.println(Arrays.toString(arr));
}
3) 알고리즘 분석
- 반복문이 두 개인 형태이므로, O(n^2)
실제로 상세하게 계산하면, {n*(n-1)}/2
참고)
Selection sort - Wikipedia
Sorting algorithm In computer science, selection sort is an in-place comparison sorting algorithm. It has an O(n2) time complexity, which makes it inefficient on large lists, and generally performs worse than the similar insertion sort. Selection sort is n
en.wikipedia.org
2. 패스트캠퍼스 '코딩 알고리즘 온라인 완주반'
3. 선택 정렬(Selection Sort) | 👨🏻💻 Tech Interview (gyoogle.dev)
선택 정렬(Selection Sort) | 👨🏻💻 Tech Interview
선택 정렬(Selection Sort) Goal Selection Sort에 대해 설명할 수 있다. Selection Sort 과정에 대해 설명할 수 있다. Selection Sort을 구현할 수 있다. Selection Sort의 시간복잡도와 공간복잡도를 계산할 수 있다. Ab
gyoogle.dev
'공부 > 알고리즘' 카테고리의 다른 글
병합 병렬(merge sort) (0) | 2022.03.03 |
---|---|
퀵 정렬(quick sort) (0) | 2022.03.03 |
삽입 정렬(insertion sort) (0) | 2022.03.03 |
버블 정렬(Bubble Sort) (0) | 2022.03.02 |