Skip to content

Instantly share code, notes, and snippets.

@m1el
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save m1el/9393243 to your computer and use it in GitHub Desktop.
Save m1el/9393243 to your computer and use it in GitHub Desktop.
trying to implement quicksort in haskell
-- 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