ID_DI
DI's study notes
ID_DI
전체 방문자
오늘
어제
  • 분류 전체보기 (85)
    • Deep-Learning (3)
      • CNN (2)
      • NLP (1)
    • Data_Python (6)
      • Numpy (0)
      • Matplotlib (4)
    • Python (8)
      • Python Algorithm (6)
    • Java (36)
      • Java(base) (33)
      • Java practice(base) (2)
    • Git (12)
    • Algorithm (7)
    • etc (7)
    • linux (1)
    • DeskSetup (0)
    • TIL_모각코 (4)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • Python
  • binarySearch
  • git
  • 자바
  • string to int
  • git add.
  • 파이썬
  • matplotlib
  • 알고리즘
  • java 기초
  • README.md
  • Github
  • 합병정렬
  • java base
  • java
  • 커밋
  • java.lang
  • staged
  • java.net
  • 정렬

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
ID_DI

DI's study notes

[알고리즘] selectionSort 선택정렬(pseudo-code, Java, 파이썬)
Algorithm

[알고리즘] selectionSort 선택정렬(pseudo-code, Java, 파이썬)

2021. 10. 14. 23:35

선택정렬

각 루프마다

  1. 최대(최소) 원소를 찾는다

  2. 최대(최소) 원소와 마지막(가장 앞에 있는) 원소를 교환한다

  3. 마지막(가장 앞에 있는) 원소를 제외한다

– 하나의 원소만 남을 때까지 위의 루프를 반복

pseudo 코드

배열 끝에서부터 나머지 원소들 중 최대값과 교환하는 방식

Algorithm selectionSort(a,n)
    for i = n-1 down to 1
        //a[0]부터 a[i]까지 중 가장 큰 원소의 위치 index를 찾는다.
        index = 0
        for j = 1 to i
            if(a[index] < a[j]) then
            index = j
        //a[index]와 a[i]를 교환한다.
        int temp = a[index]
        a[index] = a[i]
        a[i] = temp

python 코드

배열 처음부터 나머지 원소들 중 최소값과 교환하는 방식

def selection_sort(arr):
    for i in range(len(arr)-1): #마지막원소는 이미 정렬되있음
        min_index = 0
        for j in range(i+1, len(arr)):
            if arr[i] > arr[min_index]:
                min_index = j
          arr[i], arr[min_index] = arr[min_index], arr[i]

Java 코드

배열 처음부터 나머지 원소들 중 최소값과 교환하는 방식

public class Selection{
    public void sort(int[] arr){
        int min_index;
        int temp;

        for(int i = 0; i < arr.length-1; i++){ //마지막 원소는 정렬되있음
            min_index = 0;
            for(int j = i+1; j < arr.length; j++){
                if(arr[i] > arr[min_index]){
                    min_index = j;
                }
            }
            temp = arr[i];
            arr[i] = arr[min_index];
            arr[min_index] = arr[i];
        }
    }
}

수행시간 분석

  • 바깥 for문은 n-1 번 반복
  • 안쪽 for문 비교횟수 n번
  • 원소값 교환은 상수 시간

전체 원소 비교횟수:

n-1 + n-2 + ... + 2 + 1 = n(n-1)/2

시간복잡도 : n-1 + n-2 + …+ 2 + 1 = n(n-1)/2

T(n) = O(n^2)

'Algorithm' 카테고리의 다른 글

[알고리즘] binarySearch 이진탐색, 재귀이진탐색_분할과 정복 (pseudo-code 파이썬, Java)  (0) 2021.10.16
[알고리즘]분할과 정복 개념 및 예시  (0) 2021.10.15
[알고리즘] bubble_sort 버블정렬(pseudo-code, 파이썬, Java)  (0) 2021.10.15
[알고리즘] Stable & In-place  (0) 2021.10.14
알고리즘에 대하여 (pseudo-code)  (0) 2021.09.07
    'Algorithm' 카테고리의 다른 글
    • [알고리즘]분할과 정복 개념 및 예시
    • [알고리즘] bubble_sort 버블정렬(pseudo-code, 파이썬, Java)
    • [알고리즘] Stable & In-place
    • 알고리즘에 대하여 (pseudo-code)
    ID_DI
    ID_DI
    Computer Vision

    티스토리툴바