import java.util.Arrays;
class Solution {
public String[] solution(String[] strings, int n) {
// 선택 정렬 알고리즘을 사용하여 문자열 배열을 정렬합니다.
for (int i = 0; i < strings.length - 1; i++) { // 1. i는 0부터 시작하여 배열의 길이보다 1 작을 때까지 반복
int minIndex = i; // 2. minIndex를 i로 초기화합니다.
for (int j = i + 1; j < strings.length; j++) { // 3. j는 i + 1부터 시작하여 배열의 길이보다 작을 때까지 반복
char c1 = strings[minIndex].charAt(n); // 4. c1에 strings[minIndex]의 n번째 문자를 저장합니다.
char c2 = strings[j].charAt(n); // 5. c2에 strings[j]의 n번째 문자를 저장합니다.
if (c1 == c2) { // 6. c1과 c2가 같은 경우
if (strings[minIndex].compareTo(strings[j]) > 0) { // 7. strings[minIndex]와 strings[j]를 비교하여 strings[minIndex]가 더 큰 경우
minIndex = j; // 8. minIndex를 j로 업데이트합니다.
}
} else if (c1 > c2) { // 9. c1이 c2보다 큰 경우
minIndex = j; // 10. minIndex를 j로 업데이트합니다.
}
}
// 11. 현재 인덱스와 minIndex를 가진 요소를 교환합니다.
String temp = strings[i];
strings[i] = strings[minIndex];
strings[minIndex] = temp;
}
// 12. 정렬된 문자열 배열을 반환합니다.
return strings;
}
}
위 코드는 문자열 내 마음대로 정렬하기 문제를 선택 정렬(selection sort) 알고리즘을 이용하여 해결한 코드입니다.
주석을 달아 코드의 진행 순서에 대해 자세히 설명하면 다음과 같습니다.