CS/알고리즘
[정렬] 선택정렬
지잉지잉
2021. 8. 28. 15:44
- 선택정렬 (Selection Sort)
- 가장 작은 원소를 찾아 앞의 데이터와 자리 교환하는 정렬방식.
- 예) [2, 3, 1, 5, 4] 배열에서 원소 "1"은 가장 작은 원소이므로 원소 "2"와 자리교환 -> [1, 3, 2, 5, 4]
- 구현
public static void main(String[] args) {
int[] array = {2, 4, 3, 5, 1};
int length = array.length;
for (int i = 0; i < length - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < length; j++) {
if (array[minIndex] > array[j]) minIndex = j;
}
int temp = array[i];
array[i] = array[minIndex];
array[minIndex] = temp;
}
}
- for문 2번에 시간복잡도는 O(N^2)