Advertisement
jdriselvato

Untitled

Feb 24th, 2022
1,379
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.54 KB | None | 0 0
  1. import Foundation
  2.  
  3. // Binary Heap Operations & Heapsort - attempt 3
  4. /* Purpose of this attempt
  5.  * I had to use countless videos and blogs to finally understand Binary Heaps and Heapify.
  6.  * So let see if I understand it strong enough to program it from scratch.
  7.  */
  8.  
  9. let shuffled = [100,40,50,10,15,50]
  10.  
  11. print("Original:", shuffled)
  12.  
  13. helper(shuffled) // start
  14.  
  15. func helper(_ array: [Int]) -> [Int] {
  16.     var temp = array
  17.     // heapify
  18.     for i in (0 ... temp.count/2).reversed() {
  19.         heapify(&temp, i: i)
  20.     }
  21.     print("Sorted:  ", temp)
  22.    
  23.     insert(&temp, value: 40)
  24.     print("Insert:  ", temp)
  25.    
  26.    
  27.     return temp
  28. }
  29.  
  30. func insert(_ array: inout [Int], value: Int) {
  31.     array.append(value)
  32.     for i in (0 ... array.count/2).reversed() {
  33.         heapify(&array, i: i)
  34.     }
  35. }
  36.  
  37. // Returns a max heap array
  38. // i is the parent
  39. func heapify(_ array: inout [Int], i: Int) {
  40.     let left = 2 * i // left node
  41.     let right = 2 * i + 1 // right node
  42.     var max = 0
  43.    
  44.     print("For parent i: [\(i)] = \(array[i])")
  45.     print("    left \(left) | right \(right)")
  46.    
  47.    
  48.     // check if a[left] is larger than a[i]
  49.     if left <= array.count-1 && array[left] > array[i] {
  50.         max = left
  51.     } else {
  52.         max = i
  53.     }
  54.    
  55.     //    check if a[right] is larger than a[max]
  56.     if right <= array.count-1 && array[right] > array[max] {
  57.         max = right
  58.     }
  59.    
  60.     if max != i { // if i (parent) is not the max swap
  61.         array.swapAt(i, max)
  62.         heapify(&array, i: max)
  63.     }
  64. }
  65.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement