How to do bubble sort in Haskell
Bubble sort is a simple
For example, if we have a list of numbers, say [4,3,5,2], and we want them in ascending order, then the following slides describe how the bubble sort algorithm would do the job:
Note: Read more about bubble sort algorithm.
Here's how you implement bubble sort in Haskell:
bubbleSort :: Ord a => [a] -> [a]bubbleSort [] = []bubbleSort [x] = [x]bubbleSort (x:y:xs) = if x > y then y : bubbleSort (x:xs) else x : bubbleSort (y:xs)isSorted :: Ord a => [a] -> BoolisSorted [] = TrueisSorted [x] = TrueisSorted (x:y:xs) = if x > y then False else isSorted (y:xs)bubbleSortMain :: Ord a => [a] -> [a]bubbleSortMain list = if isSorted list then list else bubbleSortMain (bubbleSort list)main :: IO ()main = dolet unsortedList = [4,3,5,2]putStrLn "Unsorted list:"print unsortedListlet sortedList = bubbleSortMain unsortedListputStrLn "Sorted list:"print sortedList
Lines 1–4: The
bubbleSortfunction performs a single iteration by traversing the entirelistand swapping elements out of order in one go. To continue with the next iteration, we need to call thebubbleSortfunction again, which is done within thebubbleSortMainfunction.Lines 6–9:
isSortedfunction examines the elements of thelistand checks if they are in ascending order. It returnsTrueif the list is sorted, otherwiseFalse. This function is utilized in thebubbleSortMainfunction to decide whether further sorting is necessary.Lines 11–12: In
bubbleSortMainfunction, ifisSortedreturnsTrue, indicating that thelistis already sorted, it will stop and return the sorted list. If theisSortedfunction returnsFalse, implying that thelistis not sorted, thebubbleSortMainfunction proceeds with additional sorting iterations usingbubbleSort.Lines 14–22: The
mainfunction is used to test thebubbleSortMainfunction. Initially, the unsortedlistis printed to display its original order. Then, the unsortedlistis passed as input to thebubbleSortMainfunction. ThebubbleSortMainfunction performs the sorting process and returns the sortedlist. Finally, the sortedlistis printed to show the result of the sorting operation performed bybubbleSortMain.
Complexity
Since bubble sort algorithm is a brute-force approach, it's complexity is O(n^2) where n represents the number of elements in the list being sorted. This indicates that the time it takes to execute bubble sort grows quadratically with the input size.
Note: Read about merge sort algorithm in Haskell which does the similar job but in
O(nlogn)complexity.
Free Resources