let len;
function buildMinHeap(arr) {
    len = arr.length;
    for(let i = Math.floor(len/2); i >= 0; i--) {
        heapify(arr, i);
    }
}

function swap(items, leftIndex, rightIndex) {
    const temp = items[leftIndex];
    items[leftIndex] = items[rightIndex];
    items[rightIndex] = temp;
}

function heapify(arr, i) {
    let left = 2 * i + 1,
        right =  2* i + 2,
        min = i;
    if (left < len && arr[left] < arr[min]) {
        min = left;
    }

    if(right < len && arr[right] < arr[min]) {
        min = right;
    }

    if(min != i) {
        swap(arr, i, min);
        heapify(arr, min);
    }
}

function heapSort(arr) {
    buildMaxHeap(arr);

    for (var i = arr.length-1; i > 0; i--) {
        swap(arr, 0, i);
        len--;
        heapify(arr, 0);
    }
    return arr;
}

function top5(arr) {
    const result = arr.slice(0, 5);
    buildMinHeap(result);

    for(let i = 5; i < arr.length; i++) {
        if(arr[i] > result[0]) {
            result[0] = arr[i];
            heapify(result, 0);
        }
    }

    return result;
}

const arr = [7, 2, 9, 4, 3, 3, 5, 6, 7, 2, 5, 10]


const result = top5(arr);

console.log(result);