Skip to content

Instantly share code, notes, and snippets.

@jakswa
Created May 3, 2010 05:23
Show Gist options
  • Save jakswa/387787 to your computer and use it in GitHub Desktop.
Save jakswa/387787 to your computer and use it in GitHub Desktop.
practicing with heaps... posted at http://personal.georgiasouthern.edu/~js04714/heap.html
<html>
<head>
<title>My Heap</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<style type="text/css">
body {
font-family: monospace;
}
</style>
<script type="text/javascript">
//heap functions
function insert(heap, n) {
var i = n;
var item = heap[n];
while(i > 0 && heap[Math.floor((i-1)/2)] < item) {
heap[i] = heap[Math.floor((i-1)/2)];
i = Math.floor((i-1)/2);
}
heap[i] = item;
}
function adjust(heap, i) {
left = 2*i+1;
right = 2*i+2;
var largest = i;
if(left < heap.length && heap[left] > heap[largest])
largest = left;
if(right < heap.length && heap[right] > heap[largest])
largest = right;
if (largest != i) {
var temp = heap[i];
heap[i] = heap[largest];
heap[largest] = temp;
adjust(heap, largest);
}
}
function printHeap(heap) {
var cnt = 0;//counts length of level
var len = 1;//length of level
var color = "black";
var height = Math.floor(Math.log(heap.length)/Math.log(2)+1);
var i = 0, numspaces = 0;
var output = "";
var atStartOfLine = true;
while(i < heap.length) {
if (atStartOfLine) numspaces = Math.pow(2, height-1)-1;
else numspaces = Math.pow(2,height)-1;
for(j = 0; j < numspaces;j++)
output += "&nbsp;";
output += "<font color=\""+color+"\" >"+ heap[i]+"</font>";
i++;
cnt++;
if (i % 2 == 1)
if (color == "black")
color = "blue";
else
color = "black";
atStartOfLine = false;
if(cnt == len) {
len *= 2;
cnt = 0;
height--;
atStartOfLine = true;
output += "<br>";
}
}
return output;
}
function heapify(heap, n) {
for(i = Math.floor((n-1)/2);i>=0;i--) {
adjust(heap,i);
}
}
</script>
</head>
<body>
<script type="text/javascript">
var heap = [];
var input = prompt("Input heap values to input into a blank heap (example below)", "1,2,3,4,5").split(',');
document.write("input: "+input.toString()+"<br>");
for(i=0;i<input.length;i++) {
heap.push(input[i]);
insert(heap, heap.length-1);
}
document.write(printHeap(heap)+"<br>");
document.write("<br>deleting max node.. and then printing heap<br>");
heap[0] = heap.pop();
adjust(heap, 0);
document.write(printHeap(heap)+"<br>");
var arrForHeapify = [];
for(i=0;i<10;i++) arrForHeapify.push(i);
document.write("<br>=-=-=-==Testing Heapify =-=-=-<br>");
document.write("Array before heapify: " + arrForHeapify.toString());
heapify(arrForHeapify, arrForHeapify.length - 1);
document.write("<br>Array after heapify: " + arrForHeapify.toString());
document.write("<br>==HEAP PRINT==<br>"+printHeap(arrForHeapify));
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment