선택 정렬(Selection Sort)
2013. 6. 11. 17:00ㆍAlgorithm/정렬
아이템 수 만큼 루프를 돌면서 가장 작은 수를 찾아 가장 앞으로 보내는 정렬 방식.
원본 리스트
3 |
8 |
0 |
1 |
4 |
[STEP 1]
3 |
8 |
0 |
1 |
4 |
- [3~4] 중 최소값을 찾는다.
3 |
8 |
0 |
1 |
4 |
- 3과 0을 교환 한다.
[STEP 2]
0 |
8 |
3 |
1 |
4 |
- 0을 제외한 [8~4] 중 최소값을 찾는다.
0 |
8 |
3 |
1 |
4 |
- 8과 1을 교환한다.
[STEP 3]
0 |
1 |
3 |
8 |
4 |
- 0, 1을 제외한 [3~4] 중 최소값을 찾는다.
0 |
1 |
3 |
8 |
4 |
- 3이 최소값이므로 그대로 둔다.
[STEP 4]
0 |
1 |
3 |
8 |
4 |
- 0,1,3을 제외한 [8~4] 중 최소값을 찾는다.
0 |
1 |
3 |
8 |
4 |
- 8과 4를 교환한다.
[최종]
0 |
1 |
3 |
4 |
8 |
코드는 아래와 같다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int main(){ | |
int array[5] = {3, 8, 0, 1, 4}; | |
int i = 0, j = 0, min = 0, temp = 0; | |
for(i = 0; i < 5; i++){ | |
min = i; | |
for(j =i; j < 5; j++){ | |
if(array[j] < array[min]) | |
min = j; | |
} | |
temp = array[i]; | |
array[i] = array[min]; | |
array[min] = temp; | |
} |