module Data.Tensort.Subalgorithms.Bubblesort (bubblesort) where

import Data.Tensort.Utils.ComparisonFunctions (lessThanBit, lessThanRecord)
import Data.Tensort.Utils.Types (Record, Sortable (..), Bit)

bubblesort :: Sortable -> Sortable
bubblesort :: Sortable -> Sortable
bubblesort (SortBit [Bit]
bits) = [Bit] -> Sortable
SortBit ((Bit -> [Bit] -> [Bit]) -> [Bit] -> [Bit] -> [Bit]
forall a b. (a -> b -> b) -> b -> [a] -> b
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr Bit -> [Bit] -> [Bit]
acc [] [Bit]
bits)
  where
    acc :: Bit -> [Bit] -> [Bit]
    acc :: Bit -> [Bit] -> [Bit]
acc Bit
x [Bit]
xs = Bit -> [Bit] -> (Bit -> Bit -> Bool) -> [Bit]
forall a. a -> [a] -> (a -> a -> Bool) -> [a]
bubblesortSinglePass Bit
x [Bit]
xs Bit -> Bit -> Bool
lessThanBit
bubblesort (SortRec [Record]
recs) = [Record] -> Sortable
SortRec ((Record -> [Record] -> [Record])
-> [Record] -> [Record] -> [Record]
forall a b. (a -> b -> b) -> b -> [a] -> b
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr Record -> [Record] -> [Record]
acc [] [Record]
recs)
  where
    acc :: Record -> [Record] -> [Record]
    acc :: Record -> [Record] -> [Record]
acc Record
x [Record]
xs = Record -> [Record] -> (Record -> Record -> Bool) -> [Record]
forall a. a -> [a] -> (a -> a -> Bool) -> [a]
bubblesortSinglePass Record
x [Record]
xs Record -> Record -> Bool
lessThanRecord

bubblesortSinglePass :: a -> [a] -> (a -> a -> Bool) -> [a]
bubblesortSinglePass :: forall a. a -> [a] -> (a -> a -> Bool) -> [a]
bubblesortSinglePass a
x [] a -> a -> Bool
_ = [a
x]
bubblesortSinglePass a
x (a
y : [a]
remaningElements) a -> a -> Bool
lessThan = do
  if a -> a -> Bool
lessThan a
x a
y
    then a
x a -> [a] -> [a]
forall a. a -> [a] -> [a]
: a -> [a] -> (a -> a -> Bool) -> [a]
forall a. a -> [a] -> (a -> a -> Bool) -> [a]
bubblesortSinglePass a
y [a]
remaningElements a -> a -> Bool
lessThan
    else a
y a -> [a] -> [a]
forall a. a -> [a] -> [a]
: a -> [a] -> (a -> a -> Bool) -> [a]
forall a. a -> [a] -> (a -> a -> Bool) -> [a]
bubblesortSinglePass a
x [a]
remaningElements a -> a -> Bool
lessThan