Advertisement
Guest User

Untitled

a guest
Mar 26th, 2017
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.67 KB | None | 0 0
  1. -- This program genereates all computation steps that the
  2. -- imperative algorithm InserSort would take while sorting a list.
  3. -- The output might be further used for vizualizations of the
  4. -- alorithm behavior.
  5.  
  6. -- Example usage:
  7. -- insertSortSteps [3,2,1]
  8.  
  9. -- Result:
  10. -- [Step {i = 0, j = 1, xs = [3,2,1]},
  11. -- Step {i = 1, j = 2, xs = [3,1,2]},
  12. -- Step {i = 1, j = 1, xs = [1,3,2]}]
  13.  
  14.  
  15. -- The List that will be sorted.
  16. type Input a = [a]
  17.  
  18. -- A list of this type will be the result
  19. data ComputationStep a =
  20. Step { i :: Int
  21. , j :: Int
  22. , xs :: [a]
  23. }
  24. deriving Show
  25.  
  26.  
  27. -- Generates a list of all comutation steps the InsertSort
  28. -- algorithm takes to sort a list.
  29. insertSortSteps :: Ord a => Input a -> [ComputationStep a]
  30. insertSortSteps xs =
  31. scanl f (Step i j xs) ijs
  32. where
  33. n = length xs
  34. (i, j):ijs = [(i, j) | i <- [0..n-2], j <- [i+1,i..1]]
  35. f (Step _ _ xs) (i, j) =
  36. Step i j (updateXs xs i j)
  37.  
  38.  
  39. -- Computes new xs based on an i and a j.
  40. updateXs :: Ord a => [a] -> Int -> Int -> [a]
  41. updateXs xs i j =
  42. if (xs !! j) < (xs !! pred j)
  43. then swap xs j (pred j)
  44. else xs
  45.  
  46.  
  47. -- Swaps two elements in a list based on the given indices.
  48. swap :: [a] -> Int -> Int -> [a]
  49. swap xs i1 i2 =
  50. zipWith f xs [0..]
  51. where
  52. f x i
  53. | i == i1 = xs !! i2
  54. | i == i2 = xs !! i1
  55. | otherwise = x
  56.  
  57.  
  58. -- reminder InsertSort works like this in imperative languages, e.g. in JavaScript:
  59.  
  60. -- function insertSort (input)
  61. -- {
  62. -- const n = input.length;
  63. -- for (var i = 0; i < n-1 ; i++)
  64. -- {
  65. -- for (var j = i + 1; j >= 1; j--)
  66. -- {
  67. -- if (input[j] < input[j - 1])
  68. -- {
  69. -- swap(input, j, j - 1);
  70. -- }
  71. -- }
  72. -- }
  73. -- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement