The basic idea is as follows:
- Select successive elements in ascending order and place them into their proper position.
- Find the smallest element from the array, and exchange it with the first element.
Find the second smallest element, and exchange it with the second element;
and so on. - Repeat these procedures until the data is sorted in the proper order.
# Example
array = { 170, 45, 75, 90, 802, 24, 2, 66 };
- Smallest value 2:
170 ↔ 2 { 2, 45, 75, 90, 802, 24, 170, 66 } - Smallest value 24:
45 ↔ 24 { 2, 24, 75, 90, 802, 45, 170, 66 } - Smallest value 45:
75 ↔ 45 { 2, 24, 45, 90, 802, 75, 170, 66 } - Smallest value 66:
90 ↔ 66 { 2, 24, 45, 66, 802, 75, 170, 90 } - Smallest value 75:
802 ↔ 75 { 2, 24, 45, 66, 75, 802, 170, 90 } - Smallest value 90:
802 ↔ 90 { 2, 24, 45, 66, 75, 90, 170, 802 } - Smallest value 170:
170 ↔ 170 { 2, 24, 45, 66, 75, 90, 170, 802 } - Smallest value 802:
802 ↔ 802 { 2, 24, 45, 66, 75, 90, 170, 802 }
result = { 2, 24, 45, 66, 75, 90, 170, 802 };
# Pseudocode
arr: array
min: index of minimum value (target)
tmp: temp value
test()
for i is 0 to arr.size() - 1 do:
min := i
for j is i + 1 to arr.size() - 1 do:
if arr[j] is less than arr[min]
min := j
end for
tmp := arr[min]
arr[min] := arr[i]
arr[i] := tmp
end for
end
# Computation in C
# Time Complexity
- Worst complexity: O(n²)
- Average complexity: O(n²)
- Best complexity: O(n²)
# Space complexity
- O(1)
'Algorithms' 카테고리의 다른 글
Greedy Algorithm 그리디(탐욕) 알고리즘 (0) | 2021.08.24 |
---|---|
[Search] Linear vs. Binary 선형/이진 탐색 (0) | 2021.08.24 |
[Sorting] Insertion Sort 삽입정렬 (0) | 2021.08.24 |
[Sorting] Bubble Sort 버블정렬 (0) | 2021.08.24 |
[Sorting] Quick Sort 퀵 정렬 (0) | 2021.08.24 |