val nodeList = arrayListOf<Long?>(null)

fun main(args: Array<String>) {

    val nodeCount = readLine()!!.toInt()

    val nodeKeys = readLine()!!.split(" ")

    // ヒープに格納
    for (i in 1..nodeCount) {
        nodeList.add(i, nodeKeys[i - 1].toLong())
    }

    buildMaxHeap()

    nodeList.filterNotNull().forEach {
        print(" $it")
    }
    println()
}


fun getLeftIndex(index: Int): Int {
    return index * 2
}

fun getRightIndex(index: Int): Int {
    return index * 2 + 1
}

fun getParentIndex(index: Int): Int {
    return Math.floor(index.toDouble() / 2).toInt()
}

fun getLeftNode(index: Int): Long? {
    return nodeList.getOrNull(getLeftIndex(index))
}

fun getRightNode(index: Int): Long? {
    return nodeList.getOrNull(getRightIndex(index))
}

fun getParentNode(index: Int): Long? {
    return nodeList.getOrNull(getParentIndex(index))
}

fun maxHeapify(i: Int) {
    val myKey = nodeList[i]!!

    val leftIndex = getLeftIndex(i)
    val rightIndex = getRightIndex(i)
    val leftKey = getLeftNode(i) ?: Long.MIN_VALUE
    val rightKey = getRightNode(i) ?: Long.MIN_VALUE

    if (myKey > leftKey && myKey > rightKey) {
        // 終了
        return
    }

    if (leftKey > rightKey) {
        // swapする
        val tempMyValue = nodeList[i]
        nodeList[i] = leftKey
        nodeList[leftIndex] = tempMyValue
        maxHeapify(leftIndex)
    } else {
        // swapする
        val tempMyValue = nodeList[i]
        nodeList[i] = rightKey
        nodeList[rightIndex] = tempMyValue
        maxHeapify(rightIndex)
    }
}


fun buildMaxHeap() {
    val lastIndex = nodeList.filterNotNull().count()

    // 子供を持つ最後のノード番号
    val lastNodeIndexWithChild = getParentIndex(lastIndex)

    // ボトムアップで計算
    for (index in lastNodeIndexWithChild.downTo(1)) {
        maxHeapify(index)
    }
}
