Rei’s Tech diary

[정렬] 선택 정렬 : Selection Sort 본문

프로그래밍/Algorithm

[정렬] 선택 정렬 : Selection Sort

Reiger 2025. 1. 9. 15:00

 

📌 선택 정렬 : Selection Sort

✅ 가장 작은 값을 찾아 맨 앞에 위치시키는 정렬 알고리즘

✅ 시간 복잡도 : O(\(n^2\))

import java.util.Arrays;

public class SelectionSort {
    public static void main(String[] args) {
        int[] arr = {1, 10, 5, 8, 7, 6, 4, 3, 2, 9};

        selectionSort(arr);
        
        System.out.println("결과 : " + Arrays.toString(arr));
    }

    public static void selectionSort(int[] arr){
       int n = arr.length;

       for(int i = 0; i < n - 1; i++){
           int minIndex = i;
        
           //나머지 배열에서 최소값 찾기
           for(int j = i + 1; j < n; j++){
               if(arr[j] < arr[minIndex]){
                   minIndex = j;
               }
           }
            
           //최소값을 현재위치와 교환
           if(minIndex != i){
               int temp = arr[i];
               arr[i] = arr[minIndex];
               arr[minIndex] = temp;
           }
       }
    }
}