简体   繁体   English

在javascript中逐级打印存储为数组的堆

[英]Printing an heap memorised as an array level by level in javascript

I wanted to implement heapsort, and watch all the steps of how it works graphically,so I want to print a heap level by level.我想实现堆排序,并以图形方式观察它如何工作的所有步骤,所以我想逐层打印堆。 It ended up being much harder than actually understanding heapsort.它最终比真正理解堆排序要难得多。 Still, it would be cool to have a function to do that.尽管如此,如果有一个 function 来做到这一点,那就太酷了。 How do I do it?我该怎么做?

function printheap(a){
  let i = 0;
  let c = 0;
  let t = "\t";
  let s = " ";
  while(Math.floor(a.length/(2**i)>1)){
    t += "\t"
    i++
  }
  i = 0;
  while(Math.floor(a.length/(2**i)>1)){
    t = t.slice(0, -1)
    s += " "
    process.stdout.write(t + a[c])
    c++
    for(let j = 0; j<(2**i)-1&&c<a.length; j++){
      process.stdout.write(s + a[c])
      c++
    }
    console.log("\n")
    i++
  }
}

I tried doing it with this code, but it works funny, and pretty randomly, and I don't even know what I'm doing, and it's even pretty inefficient can anyone make a prettier solution?我试着用这段代码来做,但它工作起来很有趣,而且很随机,我什至不知道我在做什么,甚至效率很低,有人能做出更漂亮的解决方案吗?

for example given the array [3, 8, 7, 15, 17, 30, 35, 2, 4, 5, 9] I would expect something like:例如给定数组 [3, 8, 7, 15, 17, 30, 35, 2, 4, 5, 9] 我会期待这样的东西:

              3

        8          35

   15     17     30    7

 2   4  5   9

One approach is to perform an inorder traversal and consider that each next value in that order takes up its own column in the output. So you get those columns from left-to-right and the width of each column is determined by its corresponding value only.一种方法是执行中序遍历,并考虑该顺序中的每个下一个值在 output 中占据其自己的列。因此,您从左到右获得这些列,每列的宽度仅由其对应的值决定. What varies is the depth, ie the line in which the value should appear.不同的是深度,即值应该出现的行。

You could create a function for producing the inorder traversal (maybe a generator), and let it yield both the value and its depth in the tree.您可以创建一个 function 来生成中序遍历(可能是一个生成器),并让它在树中生成值及其深度。 From that information you can build up the output string:根据该信息,您可以构建 output 字符串:

 function* inorder(a, i=0, depth=0) { if (i >= a.length) return; yield* inorder(a, i*2+1, depth+1); yield [a[i], depth]; yield* inorder(a, i*2+2, depth+1); } function toString(a) { return Array.from({length: 32 - Math.clz32(a.length)}, (_, level) => Array.from(inorder(a), ([val, depth], i) => depth === level? val: " ".repeat((val+"").length) ).join(" ") ).join("\n"); } const a = [2, 5, 7, 6, 10, 9, 8, 15, 11, 18, 12, 21]; console.log(toString(a));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM