<들어가기에 앞서>
c언어로 작성된 코드입니다.
<선택 정렬이란?>
- 선택 정렬이란 단순한 정렬 시리즈 중 하나이다.
- 가장 작은 숫자를 차례대로 탐색, 가장 왼쪽 자리부터 스왑(swap)한다.
- 가장 작은 숫자를 선택하는 방식으로 정렬을 진행하여 선택 정렬이라 불린다.
- outer 루프가 한번 돌 때마다 element 하나의 최종 위치가 확정
//영상을 보면 이해가 쉬울 것이다.
https://www.youtube.com/watch?v=jtxwQ7ChiII
<Time Complextiy>
Worst : O(n^2)
Average : O(n^2)
Best : O(n^2)
<들어가기 전>
오름차순 기준으로 정렬한다.
<소스코드>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
#include <stdio.h>
void swap(int *xp,int *yp);
void printArray(int arr[],int size);
void selectionSort(int arr[],int n);
int main(void)
{
int arr[] = { 13,55,12,10,11 };
int n = sizeof(arr) / sizeof(arr[0]);
selectionSort(arr,n);
printArray(arr,n);
return 0;
}
void swap(int *xp,int *yp)
{
int temp;
temp = *xp;
*xp = *yp;
*yp = temp;
}
void selectionSort(int arr[],int n)
{
int min_index,i,j;
//내가 직접 만들어본 선택 정렬 알고리즘이다. 엉성하긴 해도 잘 작동한다.ㅎㅎ
/*int min_index = 0;
int i = 1;
while (i < n)
{
for (int count=i; count < n; count++)
{
min_index = (arr[min_index] < arr[count]) ? min_index : count;
}
swap(&arr[i-1],&arr[min_index]);
min_index = i;
i++;
}*/
for (i = 0; i < n - 1; i++)
{
min_index = i;
for (j = i + 1; j < n; j++)
{
if (arr[min_index] > arr[j])
min_index = j;
}
swap(&arr[i],&arr[min_index]);
}
}
void printArray(int arr[],int size)
{
for (int i = 0; i < size; i++)
printf("%d ",arr[i]);
}
|
cs |
<실행 결과>

틀린 부분 있으면 피드백 부탁드립니다.
감사합니다. 좋은 하루 보내세요~!
'자료구조' 카테고리의 다른 글
자료구조) 연결 리스트로 구현한 다항식 덧셈 프로그램 (1) | 2020.06.02 |
---|---|
자료구조) 역순 연결 리스트(reverse linked list) (4) | 2020.06.01 |
알고리즘) 선택 정렬(Selection Sort) (2/2) (0) | 2020.05.23 |
자료구조) Queue를 이용한 은행 시뮬레이션 프로그램 (1) | 2020.05.04 |