Last active
January 25, 2022 22:36
-
-
Save VictorTaelin/2a1cf354ea710f1eae1b6d15281813ca to your computer and use it in GitHub Desktop.
QuackSort?
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
-- merge + quick sort | |
-- quite good for random or semi-sorted lists | |
-- terrible for reverse sorted lists | |
import Debug.Trace | |
import Data.List | |
import Data.Word | |
randomList :: Word32 -> Word32 -> [Word32] | |
randomList seed 0 = [] | |
randomList seed size = seed : randomList (seed * 1664525 + 1013904223) (size - 1) | |
quacksort :: [Word32] -> [Word32] | |
quacksort [] = [] | |
quacksort [x] = [x] | |
quacksort (p : x : xs) = split p (p : x : xs) [] [] where | |
-- Splits the list in two halves of elements smaller/bigger than a pivot | |
split p [] as bs = merge (quacksort as) (quacksort bs) | |
split p (x : xs) as bs = quack p (p < x) x xs as bs | |
-- Helper function for `split` | |
quack p False x xs as bs = split p xs (x : as) bs | |
quack p True x xs as bs = split p xs as (x : bs) | |
-- Merges two lists as a sorted one | |
merge [] ys = ys | |
merge xs [] = xs | |
merge (x : xs) (y : ys) = place (x < y) x xs y ys | |
-- Helper function for `merge` | |
place False x xs y ys = y : merge (x : xs) ys | |
place True x xs y ys = x : merge xs (y : ys) | |
main :: IO () | |
main = do | |
let l = randomList 0 2000000 | |
let b = quacksort l | |
print $ sum b |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment