-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTreeSort.cs
More file actions
115 lines (97 loc) · 3 KB
/
TreeSort.cs
File metadata and controls
115 lines (97 loc) · 3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
using System;
using System.Collections.Generic;
namespace Algorithms.Sort
{
public class TreeSort : IAlgorithm
{
private int[] data = new int[12] { 7, 12, 3, 9, 4, 56, 9, 0, 2, 5, 1, 2 };
public void Run()
{
Dictionary<int, ValueContainer> tree = new Dictionary<int, ValueContainer>
{
{0, new ValueContainer {Value = data[0]}}
};
Console.WriteLine(string.Join(",", data));
for (int i = 1; i < data.Length; i++)
{
int idx = 0;
while (tree.ContainsKey(idx))
{
if (data[i] < tree[idx].Value) // left branch
{
idx = idx * 2 + 1;
continue;
}
if (data[i] > tree[idx].Value) // right branch
{
idx = idx * 2 + 2;
continue;
}
if (data[i] == tree[idx].Value)
{
tree[idx].Count++;
idx = -1;
break;
}
}
if (idx >= 0)
{
tree.Add(idx, new ValueContainer {Value = data[i]});
}
}
TraverseTree_NonRecursive(tree);
Console.WriteLine();
TraverseTree(tree);
}
private void TraverseTree_NonRecursive(Dictionary<int, ValueContainer> tree)
{
var stack = new Stack<int>();
int idx = 0;
stack.Push(idx);
while (stack.Count > 0)
{
idx = idx * 2 + 1;
if (tree.ContainsKey(idx))
{
stack.Push(idx);
continue;
}
idx = stack.Pop();
Console.Write(tree[idx] + " ");
idx = idx * 2 + 2;
if (tree.ContainsKey(idx))
{
stack.Push(idx);
//continue;
}
}
}
private void TraverseTree(Dictionary<int, ValueContainer> tree, int idx = 0)
{
int lftIdx = idx * 2 + 1;
if (tree.ContainsKey(lftIdx))
{
TraverseTree(tree, lftIdx);
}
Console.Write(tree[idx] + " ");
int rghtIdx = idx * 2 + 2;
if (tree.ContainsKey(rghtIdx))
{
TraverseTree(tree, rghtIdx);
}
}
private class ValueContainer
{
public int Value { get; set; }
public uint Count { get; set; } = 1;
public override string ToString()
{
if (Count > 1)
{
return $"{Value}({Count})";
}
return Value.ToString();
}
}
}
}