func maxHeapify(array: inout [Int], index:Int, end:Int){
var parentIndex = index
var endIndex = end
while true {
var leftChildIndex = parentIndex * 2 + 1
var rightChildIndex = leftChildIndex + 1
var childIndex = leftChildIndex
if childIndex > endIndex {
break
}
if childIndex + 1 <= endIndex && array[leftChildIndex] < array[rightChildIndex] {
childIndex += 1
}
if array[parentIndex] < array[childIndex]{
swap(&array[childIndex], &array[parentIndex])
parentIndex = childIndex
}else{
break
}
}
}
func creatMaxHeap(array: inout [Int]){
for i in (0...(array.count - 1) / 2).reversed(){
maxHeapify(array: &array, index: i, end: array.count - 1)
}
}
func heapSort(array: inout [Int]){
creatMaxHeap(array: &array)
for i in (0...array.count - 1).reversed(){
if i != 0{
swap(&array[0], &array[i])
}
maxHeapify(array: &array, index: 0, end: i - 1)
}
}