Created
April 1, 2019 12:38
-
-
Save standinga/f562011721c871d0b617bca51d328ecf to your computer and use it in GitHub Desktop.
Heap swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Heap { | |
var a = [Int]() | |
init(_ array: [Int]) { | |
a = array | |
for i in stride(from: a.count / 2 - 1, to: 0, by: -1) { | |
bubbleDown(i) | |
} | |
} | |
mutating func add(_ e: Int) { | |
a.append(e) | |
bubbleUp(a.count - 1) | |
} | |
private mutating func swap(_ i1: Int, _ i2: Int) { | |
let temp = a[i2] | |
a[i2] = a[i1] | |
a[i1] = temp | |
} | |
private mutating func bubbleUp(_ ind: Int) { | |
var i = ind | |
while i > 0 { | |
if a[i] > a[(i - 1) / 2] { | |
swap(i, (i - 1) / 2) | |
i = (i - 1) / 2 | |
} else { | |
return | |
} | |
} | |
} | |
//return index of smaller | |
private func larger (_ i1: Int, _ i2: Int) -> Int { | |
return a[i1] > a[i2] ? i1 : i2 | |
} | |
private func isSmaller(_ i1: Int, _ i2: Int) -> Bool { | |
return a[i1] < a[i2] | |
} | |
private mutating func bubbleDown(_ i: Int) { | |
var k = i | |
while k * 2 <= a.count { | |
var j = 2 * k + 1 | |
if j < a.count - 1 && isSmaller(j, j + 1) { | |
j += 1 | |
} | |
if j >= a.count { | |
return | |
} | |
if !isSmaller(k, j) { | |
return | |
} | |
swap(k, j) | |
k = j | |
} | |
} | |
mutating func getMax() -> Int? { | |
guard a.count > 0 else { | |
return nil | |
} | |
let m = a[0] | |
let last = a.removeLast() | |
if a.count > 0 { | |
a[0] = last | |
bubbleDown(0) | |
} | |
return m | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment