haskell函数式编程实现的五种排序

插入排序

insert :: Int -> [Int] -> [Int]
insert x [] = [x]
insert x (y:ys)
        | x < y = x:y:ys
        | otherwise = y : insert x ys

insertSort :: [Int] -> [Int]
insertSort [] = []
insertSort (x:xs) = insert x (insertSort xs)

归并排序

merge :: [Int] -> [Int] -> [Int]
merge xs [] = xs
merge [] ys = ys
merge (x:xs) (y:ys)
        | x > y = y:merge (x:xs) ys
        | otherwise = x:merge xs (y:ys)

mergeSort :: [Int] -> [Int]
mergeSort [] = []
mergeSort [x] = [x]
mergeSort list = merge (mergeSort a) (mergeSort b)
       where 
           (a,b) = splitAt (div (length list)2) list

快速排序

quickSort :: [Int] -> [Int]
quickSort [] = []
quickSort (x:xs) = quickSort [a|a<-xs,a<=x] ++ [x] ++ quickSort [a|a<-xs,a>x]
        

冒泡排序

swaps :: [Int] -> [Int]
swaps [] = []
swaps [x] = [x]
swaps (x1:x2:xs)
       | x1 > x2 = x2 : swaps(x1:xs)
       | otherwise = x1 : swaps(x2:xs)

bubbleSort :: [Int] -> [Int]
bubbleSort xs
           | swaps xs == xs =xs
           | otherwise = bubbleSort $ swaps xs

选择排序

selectFromOri :: Int -> [Int] -> [Int]
selectFromOri _ [] = []
selectFromOri x (y:ys)
           | x == y =ys
           | otherwise = y:selectFromOri x ys


selectSort :: [Int] -> [Int]
selectSort [] = []
selectSort xs = mini : selectSort xs'
        where
            mini = minimum xs
            xs' = selectFromOri mini xs

猜你喜欢

转载自blog.csdn.net/zhuochuyu7096/article/details/80206075