//基本情報技術者試験 平成30年春期問8 makeHeap var data = [5,13,36,8,2,2,34,63,32,1,23,9,16,24,54]; var heap = []; var hnum = data.length; makeHeap(data, heap, hnum); document.write('整列後の配列 => ['+heap+']<br>'); //木構造として整形して出力 var tree = heap[0]+'<br>'; var j = 1; while (heap[Math.pow(2, j) -1]) { tree += heap.slice(Math.pow(2, j) -1, Math.pow(2, j+1) -1).toString()+'<br>'; j++; } document.write('木構造 =><div style="text-align:center">'+tree+'</div>'); function makeHeap(data, heap, hnum) { var i, k; for (i=0; i<hnum; i++) { heap[i] = data[i]; k = i; while (k > 0) { if (heap[k] > heap[parent(k)]) { swap(heap, k, parent(k)); k = parent(k); } else { break; } } } } function swap(heap, i, j) { var tmp; tmp = heap[i]; heap[i] = heap[j]; heap[j] = tmp; } function lchild(i) { return 2 * i + 1; } function rchild(i) { return 2 * i + 2; } function parent(i) { return Math.floor((i - 1) / 2); }