Implementation of the bubble sorting algorithm (Haskell vs. C)

I wrote 2 implementations of the bubble sorting algorithm in C and Haskell. Haskell implementation:

module Main where
main = do
    contents <- readFile "./data"
    print "Data loaded. Sorting.."
    let newcontents = bubblesort contents
    writeFile "./data_new_ghc" newcontents
    print "Sorting done"
bubblesort list = sort list [] False
rev  = reverse          -- separated. To see
rev2 = reverse          --  who calls the routine
sort (x1:x2:xs) acc _
    | x1 > x2           = sort (x1:xs) (x2:acc) True
sort (x1:xs) acc flag   = sort xs (x1:acc) flag
sort [] acc True        = sort (rev acc) [] False
sort _ acc _            = rev2 acc

I compared the two implementations by executing both 20 KiB files.
C takes about a second, Haskell takes about 1 min 10 seconds.
I also profiled the Haskell application:
Compilation for profiling:

C: \ Temp> ghc -prof -auto-all -O --make Main

Profile:

C: \ Temp> Main.exe + RTS -p

and got these results. This is the pseudo-code of the algorithm:

procedure bubbleSort( A : list of sortable items ) defined as:
    do
        swapped := false
        for each i in 0 to length(A) - 2 inclusive do:  
            if A[i] > A[i+1] then  
                swap( A[i], A[i+1] )  
                swapped := true  
            end if  
        end for  
    while swapped  
end procedure  

I wonder if the Haskell implementation can work faster without changing the algorithm (in fact, there are several tricks to make the algorithm work faster, but none of the implementations have these optimizations).

+3
4

, , , : ( , C) - O (1) , ( , Haskell) - O (n) O (n) ( , ). , ( , ?), , , . , , ; , , - , , Haskell.

, rev rev2, reverse ? , SCC ( " S et C ost C " ) , 5 GHC: sort ({-# SCC "rev" #-} reverse acc) [] False {-# SCC "rev2" #-} reverse acc. ; -auto-all . - , , , ( ?), :)

+11

, , , , , .

Haskell String = [Char] , , . , , String 16 32- , 64- . , , C 1 . , 16- .

( "" ). , , . ( rev). , , , 2 , .

, , .

Haskell, ST, unboxed . , ( , , , ).

+6

Haskell :

bubblesort :: (Ord a) => [a] -> [a]
bubblesort []      = []
bubblesort (x0:xs) = case bubble x0 xs of
   (xs', True)  -> bubblesort xs'
   (xs', False) -> xs'
   where bubble x1 (x2:xs) | x1 <= x2  = merge x1 False $ bubble x2 xs
                           | otherwise = merge x2 True  $ bubble x1 xs
         bubble x1 []                  = ([x1], False)
         merge x s (xs, s') = (x:xs, s || s')

, , , . case bubblesort Haskell: " , - , ".

35% , .

P.S.: :   http://bitbucket.org/mtnviewmark/haskell-playground/src/tip/cafe/

+5

, -O -O2. -O2.

, C Haskell, - Haskell Unicode. ?

  • ?
  • ?
  • ?

, (1) , C. (2), STUArray Word8 s, , C (, , ). (3), , BASIC ( , , VisualBasic ). , BASIC.

Unicode C.

+2

Source: https://habr.com/ru/post/1737875/


All Articles