C#/알고리즘 기초 익히기

선택 정렬(Select Sort)에 대해 알아보자!

ForMan_ 2024. 3. 31. 23:46

선택 정렬

  • 오름차순을 기준으로 정렬.
  • 배열의 최소값을 찾고, 그 값을 맨 앞에 위치한 원소와 교체.
  • 맨 처음 위치를 뺀 나머지 원소들도 같은 방법으로 교체.

 

<이미지 출처: https://gmlwjd9405.github.io/images/algorithm-selection-sort/selection-sort.png>


선택 정렬 C# 코드

public void Select_Sort(List<int> _list)
    {
        int indexMin;
        int temp;

        for (int i = 0; i < _list.Count - 1; i++)
        {
            indexMin = i;

            for (int k = i + 1; k < _list.Count; k++)
            {
                if (_list[k] < _list[indexMin])
                {
                    indexMin = k;
                }
            }

            temp = _list[i];
            _list[i] = _list[indexMin];
            _list[indexMin] = temp;
        }

 

  • 장점
    - 자료 이동 횟수가 미리 결정됨.

  • 단점
    - 안정성이 떨어짐.
    - 값이 같은 원소가 있는 경우 상대적인 위치가 변경될 수 있음.

<이미지 출처: https://gmlwjd9405.github.io/images/algorithm-selection-sort/sort-time-complexity.png>