1. 선택 정렬 (selection sort)
아래 순서를 반복하며 정렬하는 알고리즘
- 주어진 데이터 중 최소값을 찾음
- 해당 최소값을 데이터 맨 앞에 위치한 값과 교체함
- 맨 앞의 위치를 뺀 나머지 데이터를 동일한 방법으로 반복함
import java.util.*;
public class SelectionSort {
public static void selectionSort() {
int[] arr = new int[5];
int size = arr.length;
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
arr[i] = sc.nextInt();
}
System.out.println("정렬 전 : " + arr);
for (int i = 0; i < size - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < size; j++) {
if (arr[minIndex] > arr[j]) {
minIndex = j;
}
}
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
System.out.println("정렬 후 : " + arr);
}
}
2. 알고리즘 분석
반복문이 두개 : O(n^2)
'Algorithm > 알고리즘' 카테고리의 다른 글
그래프(Graph) (0) | 2023.01.23 |
---|---|
동적 계획법 (Dynamic Programming)과 분할 정복 (Divide and Conquer) (0) | 2023.01.20 |
재귀 용법 (recursive call) (0) | 2023.01.20 |
삽입 정렬 (insertion sort) (0) | 2023.01.19 |
버블 정렬 (bubble sort) (0) | 2023.01.19 |