Stooge sort
Appearance
Class | Sorting algorithm |
---|---|
Data structure | Array |
Worst-case performance | |
Worst-case space complexity |
Stooge sort is a recursive sorting algorithm. It is notable for its exceptionally bad time complexity of = The algorithm's running time is thus slower compared to reasonable sorting algorithms, and is slower than bubble sort, a canonical example of a fairly inefficient sort. It is, however, more efficient than Slowsort. The name comes from The Three Stooges.[1]
The algorithm is defined as follows:
- If the value at the start is larger than the value at the end, swap them.
- If there are three or more elements in the list, then:
- Stooge sort the initial 2/3 of the list
- Stooge sort the final 2/3 of the list
- Stooge sort the initial 2/3 of the list again
It is important to get the integer sort size used in the recursive calls by rounding the 2/3 upwards, e.g. rounding 2/3 of 5 should give 4 rather than 3, as otherwise the sort can fail on certain data.
Implementation
[edit]Pseudocode
[edit] 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
swap(L[i],L[j]) // Then swap them
if (j - i + 1) > 2 then // If there are at least 3 elements in the array
t = floor((j - i + 1) / 3)
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
}
Haskell
[edit]-- 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
References
[edit]Sources
[edit]- Black, Paul E. "stooge sort". Dictionary of Algorithms and Data Structures. National Institute of Standards and Technology. Retrieved 18 June 2011.
- Cormen, Thomas H.; Leiserson, Charles E.; Rivest, Ronald L.; Stein, Clifford (2001) [1990]. "Problem 7-3". Introduction to Algorithms (2nd ed.). MIT Press and McGraw-Hill. pp. 161–162. ISBN 0-262-03293-7.