Last active
August 29, 2015 13:57
-
-
Save m1el/9393243 to your computer and use it in GitHub Desktop.
trying to implement quicksort in haskell
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
-- algorithm is following: find all swaps for current step, apply them, | |
-- repeat recursively for nested set of ranges | |
import Data.Array | |
quickSortI :: (Num i, Ix i, Show i, Ord a, Show a) => | |
Array i a -> [(i, i)] -> Array i a | |
quickSortI array ranges = | |
let (swaps, ranges') = findSwaps array ranges | |
array' = array // swaps | |
in if ranges' == [] then array' | |
else quickSortI array' ranges' | |
aSkipWhile :: (Num i, Ix i) => (i -> Bool) -> i -> i -> i | |
aSkipWhile fn pos inc = | |
if fn pos then | |
aSkipWhile fn (pos+inc) inc | |
else pos | |
findSwaps :: (Num i, Ix i, Show i, Ord a, Show a) => | |
Array i a -> [(i, i)] -> ([(i, a)], [(i, i)]) | |
findSwaps array ranges = let | |
tupleJoin (a,b) (c,d) = (c++a, d++b) | |
rangeSwaps swaps array (left, right) = let | |
pivot = array!left | |
nextranges j = [t | t@(a,b) <- [(left, j-1), (j+1, right)], a < b] | |
go i j pr = let | |
i' = aSkipWhile (\x->x<=right&&array!x<=pivot) (i+1) 1 | |
j' = aSkipWhile (\x->array!x>pivot) (j-1) (-1) | |
(s, r) = go i' j' (array!j') | |
in if i' >= j' then ([(j', pivot), (left, array!j')], nextranges j') | |
else ((i', array!j') : (j', array!i') : s, r) | |
in go left (right+1) (array!right) | |
in foldl tupleJoin ([], []) $ map (rangeSwaps [] array) ranges | |
quickSort :: (Ord a, Show a) => [a] -> [a] | |
quickSort list = | |
let array = listArray (0, length list - 1) list | |
in elems $ quickSortI array [bounds array] | |
main = do | |
line <- getLine | |
let list = map read . words $ line :: [Integer] | |
print $ quickSort list |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment