Skip to content

Instantly share code, notes, and snippets.

@rurumimic
Created September 14, 2018 13:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rurumimic/2ecf77c3d06eef1f3542b18ea49ee5e6 to your computer and use it in GitHub Desktop.
Save rurumimic/2ecf77c3d06eef1f3542b18ea49ee5e6 to your computer and use it in GitHub Desktop.
Heap Sort
import Foundation
var A = [4, 10, 14, 7, 9, 3, 2, 8, 1, 16]
func left(_ i: Int) -> Int {
return i * 2 + 1
}
func right(_ i: Int) -> Int {
return i * 2 + 1 + 1
}
func parent(_ i: Int) -> Int {
return i/2
}
func maxHeapify(_ i: Int) {
let l = left(i)
let r = right(i)
var largest = i
if l < A.count {
if A[l] > A[i] {
largest = l
}
}
if r < A.count {
if A[r] > A[largest] {
largest = r
}
}
if largest != i {
let temp = A[i]
A[i] = A[largest]
A[largest] = temp
maxHeapify(largest)
}
}
func minHeapify(_ i: Int) {
let l = left(i)
let r = right(i)
var smallest = i
if l < A.count {
if A[l] < A[i] {
smallest = l
}
}
if r < A.count {
if A[r] < A[smallest] {
smallest = r
}
}
if smallest != i {
let temp = A[i]
A[i] = A[smallest]
A[smallest] = temp
minHeapify(smallest)
}
}
func solution() {
print(A)
for i in (0...A.count/2).reversed() {
maxHeapify(i)
}
print(A)
for i in (0...A.count/2).reversed() {
minHeapify(i)
}
print(A)
}
solution()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment