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)

+ Recent posts