Advertisement
Guest User

Untitled

a guest
Apr 24th, 2019
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. object HeapSort {
  2.  
  3. // functional implementation of the HeapSort algorithm
  4.  
  5. def swap(arr: Array[Int], i1: Int, i2: Int): Array[Int] = {
  6. val elem1 = arr(i1)
  7. arr.updated(i1, arr(i2)).updated(i2, elem1)
  8. }
  9.  
  10. def heapifyMax(arr: Array[Int], root: Int, heapSize: Int): Array[Int] = {
  11. val rootIdx = root
  12. val lIdx = (root + 1) * 2 - 1
  13. val rIdx = (root + 1) * 2
  14. (arr.lift(rootIdx), arr.lift(lIdx), arr.lift(rIdx)) match {
  15. case (Some(p), Some(l), Some(r)) if r > l && r > p && heapSize >= rIdx =>
  16. heapifyMax(swap(arr, rIdx, rootIdx), rIdx, heapSize)
  17. case (Some(p), Some(l), _) if l > p && heapSize >= lIdx =>
  18. heapifyMax(swap(arr, lIdx, rootIdx), lIdx, heapSize)
  19. case _ => arr
  20. }
  21. }
  22.  
  23. def buildMaxHeap(arr: Array[Int]): Array[Int] = {
  24. (Math.floor(arr.size / 2).toInt - 1 to 0 by -1).foldLeft(arr)(heapifyMax(_, _, arr.size))
  25. }
  26.  
  27. def apply(arr: Array[Int]): Array[Int] = {
  28. (arr.size - 1 to 0 by -1).foldLeft(buildMaxHeap(arr))((b, a) => heapifyMax(swap(b, 0, a), 0, a - 1))
  29. }
  30.  
  31. // sanity tests
  32. def main(args: Array[String]): Unit = {
  33. println(heapifyMax(Array(1,4,5,2,4,3,5), 0, 7).deep)
  34. println(buildMaxHeap(Array(7,4,3,0,2,1,9,5,6)).deep)
  35. println(apply(Array(7,4,3,0,2,1,9,5,6)).deep)
  36. println(apply((1 to 1000).map(_ => scala.util.Random.nextInt()).toArray).deep)
  37. }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement