用二叉数来进行排序:

    1. function BinaryTree() {
    2. var TreeNode = function(key) {
    3. this.key = key; //当前节点的值
    4. this.left = null; //左子树
    5. this.right = null; //右子树
    6. };
    7. // 根节点
    8. var root = null;
    9. var insertNode = function(node, newNode) {
    10. if (node.key > newNode.key) {
    11. if (node.left === null) {
    12. node.left = newNode;
    13. } else {
    14. insertNode(node.left, newNode);
    15. }
    16. } else {
    17. if (node.right === null) {
    18. node.right = newNode;
    19. } else {
    20. insertNode(node.right, newNode);
    21. }
    22. }
    23. };
    24. this.insert = function(key) {
    25. var newNode = new TreeNode(key);
    26. if (root === null) {
    27. root = newNode;
    28. } else {
    29. insertNode(root, newNode);
    30. }
    31. };
    32. this.init = function() {
    33. if (
    34. Object.prototype.toString.call(arr) !== '[object Array]' ||
    35. !arr.length
    36. ) {
    37. return;
    38. }
    39. for (var i = 0, len = arr.length; i < len; i++) {
    40. this.insert(arr[i]);
    41. }
    42. };
    43. this.orderTraversal = function() {
    44. if (root === null) {
    45. //传入根节点
    46. console.warn('请先初始化二叉排序树');
    47. return;
    48. }
    49. var sorted = [];
    50. var fn = function(node) {
    51. if (node !== null) {
    52. //当前节点不等于空的时候,先遍历左子树节点, 再遍历自身节点, 最后遍历右子树节点
    53. fn(node.left); //左子树
    54. sorted.push(node.key);
    55. fn(node.right); //右子树
    56. }
    57. };
    58. fn(root);
    59. return sorted;
    60. };
    61. this.init();
    62. }
    63. var arr = [8, 13, 3, 7, 19, 21, 15];
    64. // 首先构建二叉树
    65. var tree = new BinaryTree(arr);
    66. tree.orderTraversal(); // [3, 7, 8, 13, 15, 19, 21]