꼭두각시 정렬
![]() 꼭두각시 정렬의 시각화 (swap만 보여주고 있음) | |
분류 | 정렬 알고리즘 |
---|---|
자료 구조 | 배열 |
최악 시간복잡도 | O(nlog 3/log 1.5) |
공간복잡도 | O(n) |
꼭두각시 정렬 또는 스투지 정렬(stooge sort)은 재귀 정렬 알고리즘이다. O(nlog 3 / log 1.5 ) = O(n2.7095...)이라는 예외적으로 나쁜 시간 복잡도로 유명하다. 그러므로 이 알고리즘의 실행 시간은 타당한 정렬 알고리즘들에 비해 더 느리며 상당히 비효율적인 정렬의 전형적인 예시인 거품 정렬보다도 더 느리다. 그러나 느린 정렬보다는 더 효율적이다. 이 정렬의 명칭은 스리 스투지스에서 기원한다.[1]
이 알고리즘은 다음과 같이 정의된다:
- 시작 값이 끝의 값보다 더 크면 이 둘의 위치를 서로 바꾼다.
- 목록 안에 3개 이상의 요소가 있다면:
- 목록의 처음 2/3를 꼭두각시 정렬한다.
- 목록의 마지막 2/3을 꼭두각시 정렬한다.
- 목록의 처음 2/3을 또다시 꼭두각시 정렬한다.
구현
function stoogesort(array L, i = 0, j = length(L)-1){
if L[i] > L[j] then // If the leftmost element is larger than the rightmost element
L[i] ↔ L[j] // Swap the leftmost element and the rightmost element
if (j - i + 1) > 2 then // If there are at least 3 elements in the array
t = floor((j - i + 1) / 3) // Rounding down
stoogesort(L, i , j-t) // Sort the first 2/3 of the array
stoogesort(L, i+t, j) // Sort the last 2/3 of the array
stoogesort(L, i , j-t) // Sort the first 2/3 of the array again
return L
}
-- Not the best but equal to above
stoogesort :: (Ord a) => [a] -> [a]
stoogesort [] = []
stoogesort src = innerStoogesort src 0 ((length src) - 1)
innerStoogesort :: (Ord a) => [a] -> Int -> Int -> [a]
innerStoogesort src i j
| (j - i + 1) > 2 = src''''
| otherwise = src'
where
src' = swap src i j -- need every call
t = floor (fromIntegral (j - i + 1) / 3.0)
src'' = innerStoogesort src' i (j - t)
src''' = innerStoogesort src'' (i + t) j
src'''' = innerStoogesort src''' i (j - t)
swap :: (Ord a) => [a] -> Int -> Int -> [a]
swap src i j
| a > b = replaceAt (replaceAt src j a) i b
| otherwise = src
where
a = src !! i
b = src !! j
replaceAt :: [a] -> Int -> a -> [a]
replaceAt (x:xs) index value
| index == 0 = value : xs
| otherwise = x : replaceAt xs (index - 1) value
각주
참고자료
- Black, Paul E. “stooge sort”. 《Dictionary of Algorithms and Data Structures》. National Institute of Standards and Technology. 2011년 6월 18일에 확인함.
- Cormen, Thomas H.; Leiserson, Charles E.; Rivest, Ronald L.; Stein, Clifford (2001) [1990]. 〈Problem 7-3〉. 《Introduction to Algorithms》 2판. MIT Press and McGraw-Hill. 161–162쪽. ISBN 0-262-03293-7.