본문 바로가기

공부합시다

Selection sort

 

Selection sort

Task : From those integers that are currently unsorted, find the smallest and place it next in the sorted list

 

Input: n integers are stored in an array list[i], 0 ≤ i < n

Output: a sorted list[i], 0 ≤ i < n

Specification

for (i = 0; i < n; i++){
	Examine list[i] to list[n-1] and 
	supposed that the smallest integer is at list[min];
	Interchange list[i] and list[min];
}

 

정렬이 안 돼있는 숫자들 중 가장 작은 숫자를 찾아서 이미 정렬된 리스트의 끝에 붙인다.

 

5 6 3 4 기존의 정렬 안 된 리스트

 

5 6 3 4 가장 작은 걸 (3) 찾아서 바꾼다

3 6 5 4 정렬 안 된 것 중에서 가장 작은 걸 찾는다 (4)

3 4 5 6 정렬 된 것 뒤에 가장 작은 걸 (4) 붙인다 [붙인다기 보다는 처음 거 (i)와 바꾼다고 보면 된다]

 

My code

void swap(int *a, int *b){
    int temp = *a;
    *a = *b;
    *b = temp;
}

void selection_sort(int * list, int n){
    int i, j;
    int min;
    
    for(i = 0; i < n - 1; i++){
        min = i;
        for(j = i + 1; j < n; j++){
            if(list[min] > list[j]){
                min = j;
            }
        }
        swap(&list[min], &list[i]);
    }
}

 

'공부합시다' 카테고리의 다른 글

N queen  (0) 2020.02.19
이차원벡터 선언  (0) 2019.12.29
lower_bound, upper_bound  (0) 2019.11.25
Quick Sort  (0) 2019.09.22
Binary search  (0) 2019.09.21