forked from AllAlgorithms/cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtree_sort.cpp
More file actions
72 lines (58 loc) · 1.28 KB
/
tree_sort.cpp
File metadata and controls
72 lines (58 loc) · 1.28 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
#include <iostream>
using namespace std;
struct Node
{
int key;
struct Node *left, *right;
};
struct Node *newNode(int item)
{
struct Node *temp = new Node;
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}
void storeSorted(Node *root, int arr[], int &i)
{
if (root != NULL)
{
storeSorted(root->left, arr, i);
arr[i++] = root->key;
storeSorted(root->right, arr, i);
}
}
Node* insert(Node* node, int key)
{
if (node == NULL) return newNode(key);
if (key < node->key){
node->left = insert(node->left, key);
}else if (key > node->key) {
node->right = insert(node->right, key);
}
return node;
}
void treeSort(int arr[], int n)
{
struct Node *root = NULL;
root = insert(root, arr[0]);
for (int i=1; i<n; i++){
insert(root, arr[i]);
}
int i = 0;
storeSorted(root, arr, i);
}
int main()
{
int arr[] = {12, 11, 13, 5, 6, 7};
int n = sizeof(arr)/sizeof(arr[0]);
cout << "Given array is ";
for (int i=0; i<n; i++){
cout << arr[i] << " ";
}
treeSort(arr, n);
cout << "\nSorted array is ";
for (int i=0; i<n; i++){
cout << arr[i] << " ";
}
return 0;
}