Running heap_starter.js

➕︎ Aa ➖︎ |Dark 1Dark 2Light|HackFira Code|Back to  PT Mono
// CPCS 223 Analysis & Design of Algorithms
// Heap datastructure and heapsort
// 2016, <your name etc.>


// -----------------------------------------------------------------------
// straightforward implementation of the textbook algorithm
// a generic implementation that is almost language independent

// your code here, use heapShow() to generate output



// --------------------
// heap printer: 
// pass heap array h, heap size assumed to be in first array element
// fixed to handle n<2 correctly

function heapShow(h)
{
	var n = h[0];
	var out="<p>Heap (size="+n+")";
	if (n<1) return out+"</p>";       // empty
	
	var m = (n>1)? Math.floor(n/2): 1;   // last parent (handle n=1 case)
	out+=": "+ h.slice(1,n+1)+ "</p>";
	for (var i=1; i<=m; i++)
	{
		out += "<p>"+ i+ ": <b>"+ h[i]+ "</b><ul>";
		if ( 2*i <= n )
			out += "<li>"+ h[2*i]+ "</li>";
		if ( 2*i+1 <= n )
			out+= "<li>"+ h[2*i+1]+ "</li>";
		out+= "</ul></p>";
	}
	
	return out;
}