简体   繁体   中英

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. 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          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. 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. From that information you can build up the output string:

 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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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