Skip to content

Commit 6a71123

Browse files
committed
#29 Added Tree Sort
1 parent 61c3c13 commit 6a71123

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

README.md

+2
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@
1717
- [Counting Sort](https://github.com/Zircoz/Sorting-Algorithms-in-Python/blob/master/counting_sort.py)
1818
- [Heap Sort](https://github.com/blackeye735/Sorting-Algorithms-in-Python/blob/master/Heapsort.py)
1919
- [Bucket Sort](https://github.com/Zircoz/Sorting-Algorithms-in-Python/blob/master/bucket_sort.py)
20+
-[Tree Sort](https://github.com/Zircoz/Sorting-Algorithms-in-Python/blob/master/tree_sort.py)
21+
2022

2123
## Proposed List of Sorting Algos:
2224

tree_sort.py

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
class node:
2+
def __init__(self, val):
3+
self.val = val
4+
self.left = None
5+
self.right = None
6+
7+
def insert(self, val):
8+
if self.val:
9+
if val < self.val:
10+
if self.left is None:
11+
self.left = node(val)
12+
else:
13+
self.left.insert(val)
14+
elif val > self.val:
15+
if self.right is None:
16+
self.right = node(val)
17+
else:
18+
self.right.insert(val)
19+
else:
20+
self.val = val
21+
22+
23+
def inorder(root, res):
24+
if root:
25+
inorder(root.left, res)
26+
res.append(root.val)
27+
inorder(root.right, res)
28+
29+
30+
def tree_sort(arr):
31+
if len(arr) == 0:
32+
return arr
33+
root = node(arr[0])
34+
for i in range(1, len(arr)):
35+
root.insert(arr[i])
36+
res = []
37+
inorder(root, res)
38+
return res
39+
40+
def printList(arr):
41+
for i in range(len(arr)):
42+
print(arr[i],end=" ")
43+
print()
44+
45+
# driver code to test the above code
46+
arr = [1, 12, 11, 2, 13, 5, 6, 7]
47+
print ("Given array is", end="\n")
48+
printList(arr)
49+
tree_sort(arr)
50+
print("Sorted array is: ", end="\n")
51+
printList(arr)

0 commit comments

Comments
 (0)