JSFiddle - React, Tailwind, and code Playground

by puuga

HTML

<input id="input" type="text" size="50" value="3,6,9,2,1,0,5,4,7,8"><br/>
<input type="button" onclick="doHeapSort()" value="do heap sort">
<div id="output"></div>

JavaScript

// heap sort

function doHeapSort() {
    var arr = $("#input").val().split(",");
/*
    alert(arr);
    swap(arr,4,5);
    alert(arr);
    alert("left of index 0 is "+left(0));
    alert("right of index 0 is "+right(0));
    alert("parent of index 1 is "+parent(1));
    alert("parent of index 2 is "+parent(2));
    */
    //alert(arr);
    heapSort(arr);
    //alert(arr);
    $("#output").html(arr.toString());
}

function heapSort(arr) {
    //step 1 setup heap
    var heap = [];
    while (arr.length > 0) {
        heap.push(arr.shift());
        var index = heap.length - 1;
        //alert(heap[index]);
        while (index != 0) {
            //alert(heap[index] + ">" + heap[parent(index)])
            if (heap[index] < heap[parent(index)]) {
                swap(heap, index, parent(index));
                index = parent(index);
            } else {
                break;
            }
        }
        //alert(heap);
    }
    //alert(heap);
    //step 2 do heap sort
    //output = [];
    while (heap.length > 0) {
        //alert("heap="+heap);
        arr.push(heap.shift());
        //heap.unshift(heap.pop());
        //alert("arr="+arr);
        var index = 0;
        while (index < heap.length - 1) {
            /*
            if(heap[left(index)]==undefined || heap[right(index)]==undefined){
                break;
            }
            */
            if (heap[index] > heap[left(index)]) {
                swap(heap, index, left(index));
                index = left(index);
            } else if ((heap[index] > heap[right(index)])) {
                swap(heap, index, right(index));
                index = right(index);
            } else {
                break;
            }
        }
    }
}

function left(i) {
    return 2 * i + 1;
}

function right(i) {
    return 2 * i + 2;
}

function parent(i) {
    return Math.floor((i - 1) / 2);
}

function swap(arr, x, y) {
    var temp = arr[x];
    arr[x] = arr[y];
    arr[y] = temp;
}